I have a little problem, I try to build a language learning website using React,
this is my initial homepage, and when i try to search for a word and that word doesn't exist in the database my website it s supposed to say "we can't find the word in our database" but that message it's generated on the top on my slideshow.. like
And i literally don't know what can i do..
my homepage code:
import React from 'react';
import Carousel from 'react-bootstrap/Carousel';
import pozika from '../images/telescop.png';
import '../../src/Ceseseu.css';
import pozika2 from '../images/door.png';
import pozika3 from '../images/threeword.png';
import pozaAbout from '../images/learnkorean.jpg';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome';
import NavbarFunction from '../pages/NavBarAndSearchSentence';
import { faCheckSquare } from '#fortawesome/free-solid-svg-icons';
function HomePageSlideShow() {
return (
<>
<div className='test '>
<Carousel>
{/* <div className='letsDoIt'> */}
<Carousel.Item interval={1000}>
<img
className='d-block w-100'
width={900}
height={500}
src={pozika}
alt='First slide'
/>
<Carousel.Caption>
<h3></h3>
<p></p>
</Carousel.Caption>
</Carousel.Item>
{/* </div> */}
<Carousel.Item interval={1000}>
<img
className='d-block w-100 '
src={pozika2}
alt='Third slide'
width={100}
height={500}
/>
<Carousel.Caption>
<h3></h3>
<p></p>
</Carousel.Caption>
</Carousel.Item>
<Carousel.Item interval={1000}>
<img
className='d-block w-100'
src={pozika3}
alt='Third slide'
width={900}
height={500}
/>
<Carousel.Caption>
<h3></h3>
<p></p>
</Carousel.Caption>
</Carousel.Item>
</Carousel>
</div>
</>
);
}
function HomePage() {
return (
<>
<HomePageSlideShow />
</>
);
}
export default HomePage;
and my function for searching process it s in another class, same class with my nav bar
import React from 'react';
import SentencesByWord from './SentencesByWord';
import { useState } from 'react';
import { Redirect } from 'react-router-dom';
import { useHistory } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import { Navbar, Nav, Form, FormControl, Button } from 'react-bootstrap';
function NavbarFunction() {
const [sentence, setSentence] = useState('');
const [fetchu, setFetchu] = useState('');
const [error, setError] = useState('');
let history = useHistory();
const FetchData = () => {
fetch(`http://localhost:8080/words/showSentences?word=` + sentence)
.then((response) => response.json())
.then(setFetchu)
.then(console.log(fetchu))
.catch(function (error) {
console.log('mergi');
setError("We can't find the word in our database");
});
history.push('/home');
};
const OnChangerr = (e) => {
setSentence(e.target.value);
};
const HandleKeypress = (e) => {
if (e.keyCode === 13) {
FetchData();
}
};
return (
<>
<div className='inlineu'>
<Navbar bg='dark' variant='dark'>
<Navbar.Brand href='Home'>LearningVocab</Navbar.Brand>
<Nav className='mr-auto'>
<Nav.Link href='GiveMeSentences'>
Random Sentences
</Nav.Link>
<Nav.Link href='SendEmail'>
Send us your thoughts
</Nav.Link>
<Nav.Link href='SearchByWord'>Pricing</Nav.Link>
</Nav>
<Form inline>
<FormControl
type='text'
placeholder='Search'
className='mr-sm-2'
onChange={OnChangerr}
onKeyDown={HandleKeypress}
/>
<Button variant='outline-info' onClick={FetchData}>
Search
</Button>
</Form>
</Navbar>
</div>
{fetchu ? (
<div>
<h1> {fetchu.korfirstSentence} </h1>
<h1>{fetchu.kosecondSentence}</h1>
<h1>{fetchu.kothirdSentence}</h1>
<h1>{fetchu.kowordTranslation}</h1>
<h1>{fetchu.kowordId}</h1>
</div>
) : (
// <h1> {fetchu.kosecondSentence} </h1>
<h1 className='someSpace'>{error}</h1>
)}
</>
);
}
export default NavbarFunction;
i used boostrap for css
My react component tree:
Related
picture of the output https://i.stack.imgur.com/5kxvb.png
code of the carousel
import React from 'react'
import AliceCarousel from 'react-alice-carousel';
import { Link } from 'react-router-dom';
import UseAxios from '../hooks/UseAxios'
import "./Trending.css";
const Trending = () => {
const { response } = UseAxios("search/trending");
return (
{response && response.coins.map(coin => {
return <div className='flex slide' key={coin.item.coin_id}>
<Link to={`/coin/${coin.item.id}`}>
<div>
<AliceCarousel
mouseTracking
infinite
autoPlayInterval={1000}
animationDuration={1500}
disableButtonsControls
autoPlay
>
<img src={coin.item.large} className="mt-0 relative top-30 img" />
<p key={coin.item.coin_id} className="name"> {coin.item.name} </p>
</AliceCarousel>
</div>
</Link>
</div>
})}
</div>
)
}
export default Trending;
note:- library being used is AliceCarousel.
can someone please help me fix the carousel.
Sorry for my bad English speak please help me to build a responsive sidebar menu. when i try to build a sidebar menu responsive I reach this type of error : TypeError: document.getElementByClassName is not a function. I haven't an idea where's the error exactly so this is my code of the sidebar menu:
import React from 'react';
import {useEffect} from 'react';
import SideNav, { Toggle, Nav, NavItem, NavIcon, NavText } from '#trendmicro/react-sidenav';
import '#trendmicro/react-sidenav/dist/react-sidenav.css';
import {listProducts} from '../actions/productActions';
import {useSelector, useDispatch} from 'react-redux';
function w3_open() {
document.getElementByClassName("sidebar").style.width = "100%";
document.getElementByClassName("sidebar").style.display = "block";
}
function w3_close() {
document.getElementByClassName("sidebar").style.display = "none";
}
export default function SideBarMenu() {
const dispatch = useDispatch();
useEffect(()=> {
dispatch(listProducts);
}, [])
const productList = useSelector((state) => state.productList);
const {products} = productList;
console.log(products);
return (
<div className="wrapper" >
<div className="section">
<div className="top_navbar">
<div className="hamburger">
<a href="#">
<i className="fa fa-bars" onClick={w3_open(), w3_close()} ><span className="bar-icon"> All products </span></i>
</a>
</div>
</div>
</div>
<div className="sidebar">
profile image & text
menu item
</div>
</div>
)
}
and this is the app.js file :
import React from 'react';
import {BrowserRouter, Routes, Route} from 'react-router-dom';
import HomePage from './Pages/HomePage';
import ProductPage from './Pages/productPage';
import SideBarMenu from './components/SideBarMenu';
function App() {
return (
<BrowserRouter>
<div className="grid-container" >
<header className="row" >
<div>
<a className="brand" href="/">My shop</a>
</div>
<div>
Cart
Sign In
</div>
</header>
<main>
<SideBarMenu ></SideBarMenu>
<Routes>
<Route path='/product/:id' element={<ProductPage /> } />
<Route path='/' element={<HomePage />} exact />
</Routes>
</main>
<footer className="row center" >All right reserved</footer>
</div>
</BrowserRouter>
);
}
export default App;
document.getElementByClassName(...) doesn't exist in JavaScript. You should use document.getElementsByClassName(...) (notice the plural in Elements).
Replace document.getElementByClassName("sidebar") with document.getElementsByClassName("sidebar")[0].
Update
To fix the error that you have right now, I would suggest to use a variable and useState Hook to display or hide the sidebar.
Example:
const [open, setOpen] = useState(false)
const handleSidebar = () => {
setOpen(!open)
}
return(
<div className = "wrapper" >
<div className = "section">
<div className = "top_navbar">
<div className = "hamburger">
<a href = "#">
<i className="fa fa-bars" onClick = {handleSidebar}><span className = "bar-icon"> All products </span></i>
</a>
</div>
</div>
</div>
{ open
? <div className = "sidebar">
profile image & text menu item
</div>
: null
}
</div>
)
I created a React app using create react app. Then i added antd. And I wanted to do some tests. I did not encounter a problem for Button, Tittle, DatePicker. But when I add Row, gives a lot of error.
Not a complex project, just a very simple test. I tried the existing solutions but I couldn't get a positive result, I still get error
App.js
import logo from "./logo.svg";
import "./App.css";
import { DatePicker, Row ,Button,Typography} from "antd";
import "antd/dist/antd.min.css";
const {Title}=Typography;
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
<DatePicker data-testid="date" />
<Button data-testid="button">Submit</Button>
<Title data-testid="title">Ant test title</Title>
<Row>row</Row>
</header>
</div>
);
}
export default App;
App.test.js
import { render, screen } from '#testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
it('date ', () => {
const { getByTestId } = render(<App />);
expect(getByTestId('date')).toBeInTheDocument();
});
it('button ', () => {
const { getByTestId } = render(<App />);
expect(getByTestId('button')).toBeInTheDocument();
});
it('title ', () => {
const { getByTestId } = render(<App />);
expect(getByTestId('title')).toBeInTheDocument();
});
Trying to put a Col component as a child of Row instead of a text
<Row>
<Col span={12}>col-12</Col>
<Col span={12}>col-12</Col>
</Row>
Like that.
import logo from "./logo.svg";
import "./App.css";
import { DatePicker, Row, Col ,Button,Typography} from "antd";
import "antd/dist/antd.min.css";
const {Title}=Typography;
function App() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
<DatePicker data-testid="date" />
<Button data-testid="button">Submit</Button>
<Title data-testid="title">Ant test title</Title>
<Row>
<Col span={12}>col-12</Col>
<Col span={12}>col-12</Col>
</Row>
</header>
</div>
);
}
export default App;
Good day everyone, I am implementing filtering functionality for a price. I have a function that implements this. When I click on the button, the name of the button itself is displayed in my console, and the product itself is not filtered. Tell me, please, what can it be? The screenshots show the console and my code are infected. Help me please.
app.js file where the whole program is located
import Navbar from './components/Navsbar'
import {useState} from "react"
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import "./App.css";
import {ListProduct} from "./ListProduct";
import data from "./service/data";
import {Home} from './Home'
import AppFilter from './components/Filter';
//import Footer from 'rc-table/lib/Footer';
function App() {
const [filter, setFilter] = useState("");
const [info, setInfo] = useState(data)
const [field,setState] = useState([]);
const searchTerm = (items, term,number) => {
let lower = term.toLowerCase();
if (term.length === 0) return items;
return items.filter((item) => {
let itemLower = item.strDrink.toLowerCase()
return itemLower.indexOf(lower)> -1;
});
};
const onUpdateSearch = (term) => {
setFilter(term);
};
const filterPost =(items,field)=>{
switch(field){
case 'moreThen1000':
return items.filter(item=>item.price > 500);
default:
return items
}
}
const onFilterSelect =(field) =>{
setState(field);
console.log(field)
};
const visible = searchTerm(info.drinks, filter)
const viewable = filterPost(info.drinks,field)
return (
<>
<Router>
<Navbar onUpdateSearch={onUpdateSearch} />
<AppFilter filter={field} onFilterSelect={onFilterSelect}/>
<Routes>
<Route exact path='/' element={<Home />} />
<Route exact path="/ListProduct" element={<ListProduct searchTerm = {visible} onFilterSelect={viewable}/>} />
</Routes>
</Router>
</>
);
}
export default App;
appFilter.js file where the buttons are stored
import React from 'react';
import './Filter.css';
import data from "../service/data";
import "bootstrap/dist/css/bootstrap.min.css";
const AppFilter = (props) => {
const buttonsData = [
{name: 'all', label: 'All cocktails'},
{name: 'moreThen1000', label: 'More expensive than 500$'}
];
const buttons = buttonsData.map(({name, label}) => {
const active = props.filter === name;
const clazz = active ? 'btn-light' : 'btn-outline-light';
return (
<button type="button"
className={`btn ${clazz}`}
key={name}
onClick={() => props.onFilterSelect(name)}>
{label}
</button>
)
})
return (
<div className="btn-group">
{buttons}
</div>
)
}
export default AppFilter;
ListProduct.js file where cards with goods are displayed
import "./ListProduct.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { Container, Row, Col, Card } from "react-bootstrap";
export const ListProduct = (props) => {
const {searchTerm, onFilterSelect} = props
const element = searchTerm.map((item, i) => {
const { strDrinkThumb, strDrink, price } = item;
return (
<div className="card">
<li key={i}>
<Container>
<Row>
<Col>
<Card style={{ width: "18rem" }}>
<Card.Img variant="top" src={strDrinkThumb} />
<Card.Body>
<Card.Title>{strDrink}</Card.Title>
<Card.Text>
{ `Alcohol shop . The price is for one glass
${price}$`}
</Card.Text>
</Card.Body>
</Card>
</Col>
</Row>
</Container>
</li>
</div>
);
});
return <div className="site">
<ul>{ element}</ul>
<div>
<footer className="page-footer font-small blue pt-4">
<div className="container-fluid text-center text-md-left">
<div className="row">
<div className="col-md-6 mt-md-0 mt-3">
<h5 className="text-uppercase">Cocktail shop</h5>
<p>Modern cocktail shop for different choices</p>
</div>
<hr className="clearfix w-100 d-md-none pb-0"/>
<div className="col-md-3 mb-md-0 mb-3">
<h5 className="text-uppercase">Our online resources</h5>
<ul className="list-unstyled">
<li>Our instagram page</li>
<li>Our site</li>
</ul>
</div>
</div>
</div>
<div className="footer-copyright text-center py-3">© 2020 Copyright:
MDBootstrap.com
</div>
</footer>
</div>
</div>;
};
I'm trying to test hoc wrapped component.
The component calls an apollo query inside.
const Header: React.FC<IProps> = ({}) => {
const { data, loading } = useMeQuery();
return (
<>
{!data?.me.verified && (
<div className="bg-red-500 p-3 text-center text-sm text-white font-bold">
<span>Please verify your email</span>
</div>
)}
<header className="py-4">
<div className="w-full px-5 xl:px-0 max-w-screen-xl bg-yellow-500 mx-auto">
<Image
src="/pineapple.png"
alt="pineapple-logo"
width="64"
height="64"
/>
{data ? (
<NextLink href="edit-profile">
<Link>
<span className="text-sm">
<FontAwesomeIcon className="text-xl" icon={faUser} />
{data?.me.email}
</span>
</Link>
</NextLink>
) : (
<div>Login</div>
)}
</div>
</header>
</>
);
};
export { Header as PureHeader };
export default withApollo()(Header);
import { render, waitFor } from "#testing-library/react";
import React from "react";
import Header, { PureHeader } from "../../src/components/Header";
import { ApolloProvider } from "#apollo/client";
import { createMockClient } from "mock-apollo-client";
import { MockedProvider } from "#apollo/client/testing";
import withApolloMocked from "../../src/apollo/__mock__/withApolloMocked";
describe("<Header />", () => {
it("renders ok", async () => {
const mockedClient = createMockClient();
render(
<ApolloProvider client={mockedClient}>
<PureHeader />
</ApolloProvider>
);
});
});
Even if I imported Pure Component without hoc, I get the same error when running the test.
However, if remove the hoc and export default Header (which is a pure component), it then passes the test... ;;;
import React from "react";
import Image from "next/image";
import { useMeQuery } from "../generated/graphql";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import { faUser } from "#fortawesome/free-solid-svg-icons";
import NextLink from "next/link";
import { Link } from "#chakra-ui/react";
import withApollo from "../apollo/withApollo";
interface IProps {}
const Header: React.FC<IProps> = ({}) => {
const { data, loading } = useMeQuery();
return (
<>
{!data?.me.verified && (
<div className="bg-red-500 p-3 text-center text-sm text-white font-bold">
<span>Please verify your email</span>
</div>
)}
<header className="py-4">
<div className="w-full px-5 xl:px-0 max-w-screen-xl bg-yellow-500 mx-auto">
<Image
src="/pineapple.png"
alt="pineapple-logo"
width="64"
height="64"
/>
{data ? (
<NextLink href="edit-profile">
<Link>
<span className="text-sm">
<FontAwesomeIcon className="text-xl" icon={faUser} />
{data?.me.email}
</span>
</Link>
</NextLink>
) : (
<div>Login</div>
)}
</div>
</header>
</>
);
};
// export { Header as PureHeader };
// export default withApollo()(Header);
export default Header;
import { render, waitFor } from "#testing-library/react";
import React from "react";
// import Header, { PureHeader } from "../../src/components/Header";
import Header from "../../src/components/Header";
import { ApolloProvider } from "#apollo/client";
import { createMockClient } from "mock-apollo-client";
import { MockedProvider } from "#apollo/client/testing";
import withApolloMocked from "../../src/apollo/__mock__/withApolloMocked";
describe("<Header />", () => {
it("renders ok", async () => {
const mockedClient = createMockClient();
render(
<ApolloProvider client={mockedClient}>
<Header />
</ApolloProvider>
);
});
});
Did I miss something? OR Is it just a bug?
I'm not quite sure how to deal with this problem...