Answer the question
In order to leave comments, you need to log in
How to open single product details using React Router?
I have a Nav component, it has two links. The first link leads to the main page, and the second one opens the Hat component. In turn, it sends a request to the server and receives an array of objects representing a list of products that, when clicked, should open a page with the price of this product. my code
const Nav = () => {
return (
<Router>
<NavLink to={"/"}>{"Foo"}</NavLink>
<NavLink to={"/male/hat"}>{"hat"}</NavLink>
<Switch>
<Route path={"/"} exact render={() => <div>'100'</div>} />
<Route path={"/male/:hat"} exact render={() => <Hat />} />
</Switch>
</Router>
);
};
const Hat = () => {
const [arrProd, setArrProd] = useState([]);
useEffect(() => {
(async () => {
await fetch(`https://foo0022.firebaseio.com//male/hat.json`)
.then(res => res.json())
.then(arr => setArrProd(Object.values(arr).flat()));
})();
}, []);
console.log(arrProd);
return (
<Fragment>
{arrProd.map(({ to, id, price, title }) => (
<Fragment key={id}>
<br />
<NavLink to={`/male/hat/${to}`}>{title}</NavLink>
<Route
exact
path={`/male/hat/${to}`}
render={() => <div>{price}</div>}
/>
</Fragment>
))}
</Fragment>
);
};
Answer the question
In order to leave comments, you need to log in
Step 1. Change the router:
<Switch>
<Route path={"/"} exact render={() => <div>'100'</div>} />
<Route path={"/male/hat"} exact component={ProductsList} />
<Route path={"/male/hat/:to"} exact component={ProductDetails} />
</Switch>
const ProductDetails = ({ match }) => {
const { to } = match.params;
const [state, setState] = useState({ isFetching: true, hat: null });
const { isFetching, product } = state;
useEffect(() => {
(async () => {
await fetch(`https://foo0022.firebaseio.com//male/hat.json`)
.then(res => res.json())
.then(data => {
const product = data.find(item => item.to === to);
setState({ isFetching: false, product });
});
})();
}, []);
if (isFetching) return <div>...Loading</div>;
if (!product) return <div>404: Product not found</div>;
return (
<div>
<h1>{product.title}</h1>
<h2>{product.price}</h2>
</div>
);
}
const ProductsList = () => {
const [state, setState] = useState({ isFetching: true, products: [] });
const { isFetching, products } = state;
useEffect(() => {
(async () => {
await fetch(`https://foo0022.firebaseio.com//male/hat.json`)
.then(res => res.json())
.then(data => setState({ isFetching: false, products: data });
})();
}, []);
if (isFetching) return <div>...Loading</div>;
return (
<ul>
{products.map(({ to, title }) => (
<li key={to}>
<Link to={`/male/hat/${to}`}>{title}</Link>
</li>
))}
</ul>
);
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question