React Context doesn't render component - javascript

I'm using context and React Router. When I created my context and wrapped my components, nothing rendered. When I check the console, I can see the logged data that I'm fetching (it's coming from useEffect in AnimeContext) but the Header and HomePage components don't appear.
I'm attempting to display topTv, topAiring, and topUpcoming on the HomePage.
Here's the repo
Context file
import React, { useState, useEffect, createContext } from 'react'
const AnimeContext = createContext()
const API = "https://api.jikan.moe/v3"
const AnimeProvider = (props) => {
const urls = [
`${API}/top/anime/1/airing`,
`${API}/top/anime/1/tv`,
`${API}/top/anime/1/upcoming`,
]
// State for top Anime
const [topTv, setTopTv] = useState([])
const [topAiring, setTopAiring] = useState([])
const [topUpcoming, setTopUpcoming] = useState([])
// State for Anime details
const [animeReq, setAnimeReq] = useState({
fetching: false,
anime: []
})
// State for Anime search form
const [dataItems, setDataItems] = useState([])
const [animeSearched, setAnimeSearched] = useState(false)
// Fetch top Anime
const fetchTopAnime = async () => {
return Promise.all(
urls.map(async url => {
return await fetch(url); // fetch data from urls
})
)
.then((responses) => Promise.all(responses.map(resp => resp.json())) // turn data into JSON
.then(data => {
const topTvFiltered = data[0].top.filter(item => item.rank <= 5) // filter out top 6
const topAiringFiltered = data[1].top.filter(item => item.rank <= 5)
const topUpcomingFiltered = data[2].top.filter(item => item.rank <= 5)
setTopTv(topTvFiltered)
setTopAiring(topAiringFiltered)
setTopUpcoming(topUpcomingFiltered)
console.log(data)
})
)
.catch(err => console.log("There was an error:" + err))
}
useEffect(() => {
fetchTopAnime()
}, [])
// Fetch Anime details
const fetchAnimeDetails = async () => {
setAnimeReq({ fetching: true })
const response = await fetch(`${API}/${props.match.params.animeId}`)
const data = await response.json()
console.log(data);
setAnimeReq({ fetching: false, anime: data }) // set initial state to hold data from our API call
}
// Fetch searched Anime
const handleSubmit = async (e) => {
e.preventDefault()
const animeQuery = e.target.elements.anime.value
const response = await fetch(`${API}/search/anime?q=${animeQuery}&page=1`)
// const response2 = await fetch(`${API}/top/anime/1/movie`)
const animeData = await response.json()
// const topAnime = await response2.json()
setDataItems(animeData.results)
setAnimeSearched(!animeSearched)
props.history.push('dashboard')
}
const { fetching, anime } = animeReq;
return (
<AnimeContext.Provider value={{
topTv,
setTopTv,
topAiring,
setTopAiring,
topUpcoming,
setTopUpcoming,
dataItems,
setDataItems,
animeSearched,
setAnimeSearched,
fetching,
anime,
fetchTopAnime,
fetchAnimeDetails,
handleSubmit
}}>
{props.childen}
</AnimeContext.Provider>
)
}
export { AnimeProvider, AnimeContext }
App.js
import React, { Component } from 'react';
import styled, { ThemeProvider } from 'styled-components';
import theme from './config/theme';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import { AnimeProvider } from './store/AnimeContext'
import Header from './Components/Header';
import HomePage from './Components/Home Page/HomePage';
import AnimeDetails from './Components/AnimeDetails';
import AnimeCard from './Components/AnimeCard/AnimeCard'
class App extends Component {
render() {
return (
<AnimeProvider>
<Router>
<ThemeProvider theme={theme}>
<AppWrapper>
<Header />
<Switch>
<Route path='/' exact component={HomePage} />
<Route path='/dashboard' exact component={AnimeCard} />
<Route path='/:animeId' component={AnimeDetails} />
</Switch>
</AppWrapper>
</ThemeProvider>
</Router>
</AnimeProvider>
);
}
}
const AppWrapper = styled.div`
text-align: center;
font-size: calc(10px + 1vmin);
color: white;
`
export default App;
HomePage Component
import React, { useContext } from 'react'
import styled from 'styled-components'
import { TopAnime } from './TopAnime';
import { AnimeContext } from '../../store/AnimeContext'
const HomePage = () => {
const [topTv, topAiring, topUpcoming,] = useContext(AnimeContext)
return (
<AnimeContext.Consumer>
<HomeWrapper>
<TopAni>
{topTv.length > 0 ? <TopAniTitle>Top TV</TopAniTitle> : null}
{topTv.map((item, index) => (
<TopAnime
key={index}
image={item.image_url}
title={item.title}
item={item}
/>
))}
</TopAni>
<TopAni>
{topAiring.length > 0 ? <TopAniTitle>Top Airing</TopAniTitle> : null}
{topAiring.map((item, index) => (
<TopAnime
key={index}
image={item.image_url}
title={item.title}
item={item}
/>
))}
</TopAni>
<TopAni>
{topUpcoming.length > 0 ? <TopAniTitle>Top Upcoming</TopAniTitle> : null}
{topUpcoming.map((item, index) => (
<TopAnime
key={index}
image={item.image_url}
title={item.title}
item={item}
/>
))}
</TopAni>
</HomeWrapper>
</AnimeContext.Consumer>
);
}
const HomeWrapper = styled.div`
height: 100%;
padding: 6rem 4.5rem;
color: ${props => props.theme.colors.white};
`
const TopAni = styled.div`
max-width: 1200px;
margin: 0 auto;
display: grid;
grid-gap: 1rem;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-template-rows: auto;
padding: 1rem;
`
const TopAniTitle = styled.h2`
grid-column: 1 / -1;
justify-self: start;
`
export default HomePage
If I move my AnimeProvider below the Header, I am able to view the header like so:
return (
<Router>
<ThemeProvider theme={theme}>
<AppWrapper>
<Header />
<Switch>
<AnimeProvider>
<Route path='/' exact component={HomePage} />
<Route path='/dashboard' exact component={AnimeCard} />
<Route path='/:animeId' component={AnimeDetails} />
</AnimeProvider>
</Switch>
</AppWrapper>
</ThemeProvider>
</Router>
);
So I'm either missing something crucial or I'm not understanding how Context works and/or React Router.

You have a typo in AnimeProvider - it should render {props.children} not {props.childen}

AnimeContext.Consumer requires a function as a child, also if you are using useContext then there is no need to wrap your component with AnimeContext.Consumer in first place.
Also since your provider pass down an object, then useContext would return an object, so you need object destructuring instead of array destructuring.
const HomePage = () => {
const { topTv, topAiring, topUpcoming } = useContext(AnimeContext)
return (
<HomeWrapper>
<TopAni>
{topTv.length > 0 ? <TopAniTitle>Top TV</TopAniTitle> : null}
{topTv.map((item, index) => (
<TopAnime
key={index}
image={item.image_url}
title={item.title}
item={item}
/>
))}
</TopAni>
...
</HomeWrapper>
}
}

Related

why my react project always warning:Maximum update depth exceeded at Navigate

**can someone help me why my project run a alots error about this?
I don't see any question about my codes.
Here is error:
Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
at Navigate (http://localhost:3000/static/js/bundle.js:161563:5)
at div
at O (http://localhost:3000/static/js/bundle.js:168705:6)
at div
at O (http://localhost:3000/static/js/bundle.js:168705:6)
at div
at O (http://localhost:3000/static/js/bundle.js:168705:6)
at Product (http://localhost:3000/static/js/bundle.js:1761:5)
at section
at O (http://localhost:3000/static/js/bundle.js:168705:6)
at Products
at div
at O (http://localhost:3000/static/js/bundle.js:168705:6)
at ProductList
at RenderedRoute (http://localhost:3000/static/js/bundle.js:161243:5)
at Routes (http://localhost:3000/static/js/bundle.js:161692:5)
at Router (http://localhost:3000/static/js/bundle.js:161623:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:159844:5)
at App
here are the relative codes:
App.jsx.
This one is setting path for the route.
import React from 'react'
import Cart from './pages/Cart'
import Home from './pages/Home'
import Login from './pages/Login'
import Product from './pages/Product'
import ProductList from './pages/ProductList'
import Register from './pages/Register'
import { BrowserRouter as Router, Navigate, Route, Routes } from "react-router-dom";
const App = () => {
const user = true;
return (
<Router>
<Routes>
<Route exact path="/" element={<Home />} />
<Route exact path="/products/:category" element={<ProductList />} />
<Route exact path="/product/:id" element={<Product />} />
<Route exact path="/cart" element={<Cart />} />
<Route exact path="/register" element={user ? <Navigate to="/" /> : <Register />} />
<Route exact path="/login" element={user ? <Navigate to="/" /> : <Login />} />
</Routes>
</Router>
)
}
export default App
Product.jsx This one is running product information,it's also a component.
**When I run the url:http:localhost:3000/products/women,it should be show the products belongs to the category:women.**But it runs http:localhost:8000/products/productId,it's wrong.
import React from 'react'
import { useEffect, useState } from 'react';
import Product from './Product';
import axios from "axios"
const Products = ({ cate, filters, sort }) => {
//const Products = () => {
console.log(cate, filters, sort)
const [products, setProducts] = useState([]);
const [filteredProducts, setFilteredProducts] = useState([]);
useEffect(() => {
const getProducts = () => {
const res = axios.get(
cate ? `http://localhost:8000/api/products?category=${cate}`
: "http://localhost:8000/api/products")
.then(
function (res) {
setProducts(res.data);
console.log(res)
}
).catch(
function (err) {
console.log(err)
});
}
getProducts();
}, [cate]);
useEffect(() => {
cate && setFilteredProducts(
products.filter((item) => (
Object.entries(filters).every(([key, value]) => {
return item[key].includes(value);
}
)
))
)
}, [products, cate, filters])
useEffect(() => {
if ((sort === "newest")) {
setFilteredProducts((prev) =>
[...prev].sort((a, b) => a.createdAt.localeCompare(b.createdAt))
)
} else if (sort === "asc") {
setFilteredProducts((prev) =>
[...prev].sort((a, b) => a.price - b.price)
)
} else {
setFilteredProducts((prev) =>
[...prev].sort((a, b) => b.price - a.price)
)
}
})
return (
<Container >
{cate
? filteredProducts.map((item) => (
<Product item={item} key={item._id} />))
: products.slice(0, 8).map((item) => <Product item={item} key={item._id} />)}
</Container>
);
};
pages/Product.jsx.
This one is running display part.
http:localhost:3000/product/productID**
import { useLocation } from 'react-router-dom'
import { useState, useEffect } from 'react';
import { publicRequest } from './requestMethods';
const Product = () => {
// ε›žε‚³θ·―εΎ‘
const location = useLocation();
const id = location.pathname.split("/")[2];
const [product, setProduct] = useState({});
useEffect(() => {
const getProduct = async () => {
try {
const res = await publicRequest.get("/product/find/" + id);
setProduct(res.data);
}
catch { }
}
getProduct();
}, [id])
You have to include the missing dependencies in the useEffect dependency array if not any, you can have an empty array [] as dependency
I could see a missing dep here in below effect:
useEffect(() => {
if (sort === "newest") {
setFilteredProducts((prev) =>
[...prev].sort((a, b) => a.createdAt.localeCompare(b.createdAt))
);
} else if (sort === "asc") {
setFilteredProducts((prev) => [...prev].sort((a, b) => a.price - b.price));
} else {
setFilteredProducts((prev) => [...prev].sort((a, b) => b.price - a.price));
}
},[sort]); // here `sort` is missing as dependency
Otherwise it runs on every render, which is what exactly the warning is about πŸ˜‡

How to change Title color when API data is active in React

I am working with a few APIs that report incidents, I have a collapse component with the titles of each upstream provider. If there's an active incident either based on an incident in the past 24 hours, or if it's in the active section, I would like to make the text in the collapse title red, otherwise make it green.
I created a new state variable called isActive, How would I go about this is React? The first is (App.js file and then Panels.js below.)
import React, { useEffect, useState } from "react";
import { Panels } from "./components/Panels";
import { BrowserRouter as Router, Routes, Route } from
"react-router-dom";
import Navbar from "./components/Navbar";
import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";
import Home from "./pages/Home";
import Team from "./pages/Team";
import Outages from "./pages/Outages";
function App() {
const emptyFeed = {
title: "",
link: "",
updated: "",
};
const [feed, setFeed] = useState(emptyFeed);
const [feedol, setFeedol] = useState(emptyFeed );
const [jsonData, setJsonData] = useState(emptyFeed);
const [azureData, setAzureData] = useState(emptyFeed);
const [isActive, setIsActive] = useState("false");
const getFeed = () => {
fetch("/feed")
.then((response) => response.json())
.then((data) => {
setFeed(data);
});
};
const getFeedOl = () => {
fetch("/feed_ol")
.then((response) => response.json())
.then((data) => {
setFeedol(data);
});
};
const getJsonData = () => {
fetch("/json_data")
.then((response) => response.json())
.then((data) => {
setJsonData(data["archive"][0]);
});
};
const getAzureData = () => {
fetch("/azure_data")
.then((response) => response.json())
.then((data) => {
setAzureData(data);
});
};
const getAllFour = () => {
getFeed();
getFeedOl();
getJsonData();
getAzureData();
};
useEffect(() => {
getAllFour();
}, []);
return (
<>
<Router>
<Navbar />
<Routes>
<Route exact path="/" element={<Home />} />
<Route path="/team" element={<Team />} />
<Route path="/outages" element={<Outages />} />
</Routes>
</Router>
<Panels
feed={feed}
feedol={feedol}
jsonData={jsonData}
azureData={azureData}
getAllFour={getAllFour}
/>
</>
);
}
export default App;
import React from "react";
import { Collapse } from "antd";
import { Card, Container } from "react-bootstrap";
import { BsArrowClockwise } from "react-icons/bs";
import "./panels.css";
import "antd/dist/antd.css";
const { Panel } = Collapse;
export const Panels = ({ feed, feedol, jsonData,
azureData,
getAllFour }) => {
return (
<Container>
<Card className="table-card">
<Card.Header>
{" "}
<button
type="button"
className=" refresh-button"
onClick={getAllFour}
>
{" "}
<BsArrowClockwise />
</button>{" "}
Upstream Outages{" "}
</Card.Header>
<Collapse accordion>
<Panel header={feedol.title} key="1">
<p>{}</p>
</Panel>
<Panel header={feed.title} key="2">
<p>{}</p>
</Panel>
<Panel header={azureData.title} key="3">
<p>{}</p>
</Panel>
<Panel header={jsonData.service_name} key="4">
<p>{}</p>
</Panel>
</Collapse>
</Card>
</Container>
);
};

Change color of individual items of array in React

I have fetched and displayed a list of json data:
What it currently looks like in the browser.
I want to be able to change the background color of these buttons based on the value of the property in my json file, 'era'. If composer.era === 'Renaissance', setColor('red'). If composer.era === 'Baroque', setColor('blue'), etc...
Here is some of my json for reference:
{
"name": "Giulio Caccini",
"img": "/composerImgs/Caccini.jpeg",
"era": "Baroque",
"id": 23
},
{
"name": "Giovanni Gabrieli",
"img": "/composerImgs/Gabrieli.jpeg",
"era": "Renaissance",
"id": 24
},
Here is the fetch request from that json and how I'm currently handling it:
import {useState, useEffect} from 'react'
import { Login } from './Login'
import { Timeline } from './Timeline'
import { Results } from './Results'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import { Link } from "react-router-dom"
import './App.css'
import { styled } from '#mui/material/styles'
const ComposerButton = styled('button')({
width: '12rem',
height: '12rem',
position: 'relative',
right: '1rem',
border: 'none',
borderRadius: '25px'
})
const App = () => {
const [name, setName] = useState('');
const [composers, setComposers] = useState([]);
const [color, setColor] = useState('#27856a')
useEffect(() => {
const fetchComposers = async () => {
const response = await fetch('composers.json');
const data = await response.json();
const listofComposers = data.composers.map((composer) => {
return (
<Link to='/results'>
<ComposerButton style={{backgroundColor: color}} onClick={() => setName(composer.name)} key={composer.id}>
<ComposerName>{composer.name}</ComposerName>
{/* <ComposerImg src={composer.img}/> */}
</ComposerButton>
</Link>
)
})
setComposers(listofComposers);
}
fetchComposers();
}, []);
return (
<Router>
<Routes>
<Route path='/' element={<Login code={code} />} />
<Route path='/timeline' element={<Timeline composers={composers} />} />
<Route path='/results' element={<Results name={name} code={code} />} />
</Routes>
</Router>
);
}
export default App;
How can I change color depending on composer.era's value?
I've already tried:
const listofComposers = data.composers.map((composer) => {
if (composer.era === 'Renaissance'){
setColor('red')
}
if (composer.era === 'Baroque'){
setColor('blue')
}
etc...

Commerce JS, generateToken returning "Material-UI: A component is changing the controlled value state of Select to be uncontrolled."

This is where i generate the token
import React, { useState, useEffect } from 'react';
import { Paper, Stepper, Step, StepLabel, Typography, CircularProgress, Divider, Button } from '#material-ui/core';
import { commerce } from '../../../lib/commerce';
import useStyles from './styles';
import AddressForm from '../AddressForm';
import PaymentForm from '../PaymentForm';
const steps = ['Shipping address', 'Payment details'];
const Checkout = ({ cart }) => {
const [activeStep, setActiveStep] = useState(0);
const [checkoutToken, setCheckoutToken] = useState(null);
const classes = useStyles();
useEffect(() => {
if (cart.id) {
const generateToken = async () => {
try {
const token = await commerce.checkout.generateToken(cart.id, { type: 'cart' });
setCheckoutToken(token)
} catch (error){
console.log(error);
}
};
generateToken();
}
}, [cart]);
const Confirmation = () => (
<div>
Confirmation
</div>
)
const Form = () => activeStep === 0
? <AddressForm checkoutToken={checkoutToken} />
: <PaymentForm />
return (
<>
<div className={classes.toolbar} />
<main className={classes.layout} >
<Paper className={classes.paper}>
<Typography variant='h4' align='center'>Checkout</Typography>
<Stepper activeStep={activeStep} className={classes.stepper}>
{steps.map((step) => (
<Step key={step}>
<StepLabel>{step}</StepLabel>
</Step>
))}
</Stepper>
{activeStep === steps.length ? <Confirmation /> : checkoutToken && <Form />}
</Paper>
</main>
</>
)
}
export default Checkout
Here is my App.js
import React, { useState, useEffect, Fragment } from 'react'
import { commerce } from './lib/commerce';
import { Products, Navbar, Cart, Checkout } from './components';
import { BrowserRouter as Router, Routes, Route} from 'react-router-dom';
const App = () => {
const [products, setProducts] = useState([]);
const [cart, setCart] = useState({});
const fetchProducts = async () => {
const { data } = await commerce.products.list();
setProducts(data);
}
const fetchCart = async () => {
setCart(await commerce.cart.retrieve())
}
const handleAddToCart = async ( productId, quantity) =>{
const { cart } = await commerce.cart.add(productId, quantity);
setCart(cart);
}
const handleUpdateCartQty = async (productId, quantity) => {
const { cart } = await commerce.cart.update(productId, { quantity });
setCart(cart);
}
const handleRemoveFromCart = async (productId) => {
const { cart } = await commerce.cart.remove(productId);
setCart(cart);
}
const handleEmptyCart = async () => {
const { cart } = await commerce.cart.empty();
setCart(cart);
}
useEffect(() => {
fetchProducts();
fetchCart();
}, []);
return (
<Router>
<div>
<Navbar totalItems={cart.total_items} />
<Routes>
<Route exact path='/' element={<Products products={products} onAddToCart={handleAddToCart} />} />
<Route exact path='/cart' element={<Cart cart={cart} handleUpdateCartQty={handleUpdateCartQty} handleAddToCart={handleAddToCart} handleRemoveFromCart={handleRemoveFromCart} handleEmptyCart={handleEmptyCart} />} />
<Route exact path='/checkout' element={ <Checkout cart={cart} />} />
</Routes>
</div>
</Router>
)
}
export default App;
And here is my cart.jsx incase their is anything relevant there
import React from 'react'
import { Container, Typography, Button, Grid} from '#material-ui/core';
import { Link } from 'react-router-dom';
import useStyles from './styles';
import CartItem from './CartItem/CartItem';
const Cart = ({ cart, handleUpdateCartQty, handleRemoveFromCart, handleEmptyCart }) => {
const classes = useStyles();
const EmptyCart = () => (
<Typography variant='subtitle1'>
You have no items in your shopping cart.
<Link to='/' className={classes.link}>Add Items!</Link>
</Typography>
);
const FilledCart = () => (
<>
<Grid container spacing={3}>
{ cart.line_items.map((item) => (
<Grid item xs={12} sm={4} key={item.id}>
<CartItem item={item} onUpdateCartQty={handleUpdateCartQty} onRemoveFromCart={handleRemoveFromCart} />
</Grid>
))}
</Grid>
<div className={classes.cardDetails}>
<Typography variant='h4'>
Subtotal: {cart.subtotal.formatted_with_symbol}
<div>
<Button className={classes.emptyButton} size='large' type='button' variant='contained' color='secondary' onClick={handleEmptyCart}>
Empty Cart
</Button>
<Button component={Link} to='/checkout' className={classes.checkoutButton} size='large' type='button' variant='contained' color='primary'>
Checkout
</Button>
</div>
</Typography>
</div>
</>
);
// Wait for cart to load items
if(!cart.line_items){
return '...loading';
}
return (
<Container>
<div className={classes.toolbar} />
<Typography className={classes.title} varaint='h3' gutterBottom >Your Shopping Cart</Typography>
{ !cart.line_items.length ? <EmptyCart /> : <FilledCart />}
</Container>
)
}
export default Cart
[error messages][1]
[1]: https://i.stack.imgur.com/vlard.png
Warning: Expected onSubmit listener to be a function, instead got a
value of string type. form
FormProvider#http://localhost:3000/static/js/bundle.js:76722:7
AddressForm#http://localhost:3000/static/js/bundle.js:1096:7 Form div
Paper#http://localhost:3000/static/js/bundle.js:12332:17
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25 main
Checkout#http://localhost:3000/static/js/bundle.js:1332:7
Routes#http://localhost:3000/static/js/bundle.js:67209:7 div
Router#http://localhost:3000/static/js/bundle.js:67146:7
BrowserRouter#http://localhost:3000/static/js/bundle.js:65952:7
App#http://localhost:3000/static/js/bundle.js:347:82
Warning: A component is changing a controlled input to be
uncontrolled. This is likely caused by the value changing from a
defined to undefined, which should not happen. Decide between using a
controlled or uncontrolled input element for the lifetime of the
component. More info: https://reactjs.org/link/controlled-components
input SelectInput#http://localhost:3000/static/js/bundle.js:13482:19
div InputBase#http://localhost:3000/static/js/bundle.js:8257:25
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25
Input#http://localhost:3000/static/js/bundle.js:9146:26
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25
Select#http://localhost:3000/static/js/bundle.js:13182:26
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25 div
Grid#http://localhost:3000/static/js/bundle.js:7352:29
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25 div
Grid#http://localhost:3000/static/js/bundle.js:7352:29
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25 form
FormProvider#http://localhost:3000/static/js/bundle.js:76722:7
AddressForm#http://localhost:3000/static/js/bundle.js:1096:7 Form div
Paper#http://localhost:3000/static/js/bundle.js:12332:17
WithStyles#http://localhost:3000/static/js/bundle.js:19639:25 main
Checkout#http://localhost:3000/static/js/bundle.js:1332:7
Routes#http://localhost:3000/static/js/bundle.js:67209:7

react link route not redirecting to url

I have this serch.js file. When I search and click on the li in the search result, I want to get redirected to <InnerDetail /> but the URL doesn't change or I don't get redirected to this page
but manualy if I type in the URL localhost/detiled/8 I am redirected to to <InnerDetail /> with id as 8
import React from "react";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import { faSearch } from "#fortawesome/free-solid-svg-icons";
import { useState, useEffect } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import { useHistory } from "react-router-dom";
const initialState = {
idaddProducts: "",
};
const Searchclients = () => {
const history = useHistory();
const [showResults, setShowResults] = React.useState(true);
const [poName, pnName] = React.useState(initialState);
const [showSerch, setShowSerch] = React.useState([]);
const [detail, setDetail] = useState(false);
const [inputValue, setInputValue] = React.useState("");
const [filteredSuggestions, setFilteredSuggestions] = React.useState([]);
const [selectedSuggestion, setSelectedSuggestion] = React.useState(0);
const [displaySuggestions, setDisplaySuggestions] = React.useState(false);
const suggestions = [];
showSerch.forEach(function (data) {
suggestions.push(data);
});
const onChange = (event) => {
const value = event.target.value;
setInputValue(value);
setShowResults(false);
const filteredSuggestions = suggestions.filter(
(suggestion) =>
suggestion.firstname
.toString()
.toLowerCase()
.includes(value.toLowerCase()) ||
suggestion.id.toString().toLowerCase().includes(value.toLowerCase())
);
setFilteredSuggestions(filteredSuggestions);
setDisplaySuggestions(true);
};
const onSelectSuggestion = (index) => {
setSelectedSuggestion(index);
setInputValue(filteredSuggestions[index]);
setFilteredSuggestions([]);
setDisplaySuggestions(false);
};
const SuggestionsList = (props) => {
// console.log(props);
const {
suggestions,
inputValue,
onSelectSuggestion,
displaySuggestions,
selectedSuggestion,
} = props;
if (inputValue && displaySuggestions) {
if (suggestions.length > 0) {
return (
<ul className="suggestions-list" style={styles.ulstyle}>
{suggestions.map((suggestion, index) => {
// console.log(suggestions);
const isSelected = selectedSuggestion === index;
const classname = `suggestion ${isSelected ? "selected" : ""}`;
return (
<Link to={`/detiled/${suggestion.id}`}> //this link dont work
<li
style={styles.listyle}
// onMouseOver={{ background: "yellow" }}
key={index}
className={classname}
>
{suggestion.firstname}
</li>
</Link>
);
})}
</ul>
);
} else {
return <div>No suggestions available...</div>;
}
}
return <></>;
};
useEffect(() => {
axios
.get("all-doctors-list/")
.then((res) => {
const data = res.data;
// pnName(data.data);
// var stringdata = data;
setShowSerch(data);
//console.log(stringdata);
});
// setShowSerch(data);
}, []);
return (
<>
<div className="note-container" style={styles.card}>
<div style={styles.inner}>
<p style={{ textAlign: "left" }}>Search Doctors</p>
<form className="search-form" style={{}}>
{showResults ? (
<FontAwesomeIcon
style={{ marginRight: "-23px" }}
icon={faSearch}
/>
) : null}
<input
onChange={onChange}
value={inputValue}
style={styles.input}
type="Search"
/>
<SuggestionsList
inputValue={inputValue}
selectedSuggestion={selectedSuggestion}
onSelectSuggestion={onSelectSuggestion}
displaySuggestions={displaySuggestions}
suggestions={filteredSuggestions}
/>
</form>
</div>
</div>
</>
);
};
export default Searchclients;
Navigator.js
import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import InnerDetail from "./client/doctor/components/innerto_detail.js";
class Navigator extends React.Component {
render() {
return (
<Router>
<div>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/detiled/:id">
<InnerDetail />
</Route>
</Switch>
</div>
</Router>
);
}
}
function Home() {
return (
<div style={{ paddingTop: "20%", textAlign: "center" }}>
<h1>Home</h1>
</div>
);
}
export default Navigator;
when i hover on the<li> the bottom of the browser the path is showing currectly
i think the problem is here i tried another links here nothing is working here
<Link to={`/detiled/${suggestion.id}`}> //this link dont work
<li
style={styles.listyle}
// onMouseOver={{ background: "yellow" }}
key={index}
className={classname}
>
{suggestion.firstname}
</li>
</Link>
i tryed another link under the flowing code
a button called hello and that works i think the probelm is with the return
<SuggestionsList
inputValue={inputValue}
selectedSuggestion={selectedSuggestion}
onSelectSuggestion={onSelectSuggestion}
displaySuggestions={displaySuggestions}
suggestions={filteredSuggestions}
/>
<Link
to={{
pathname: `/detiled/5`,
}}
>
<button>hello</button>
</Link>
try using
<Route path="/detiled/:id" component={InnerDetail} />
instead of
<Route path="/detiled/:id">
<InnerDetail />`
in Navigator.js
and
Route exact path="/">
<Home />
did you created any Home component, and not imported that in Navigator.js
<Link to={"/detiled/"+ suggestion.id}><li>...</li></Link>
this worked for me

Categories

Resources