I want to build a page when from list of products I want to see product by ID. In my App file I have something like that:
<Route path={ROUTES.product} element={<Product id={1} />}>
but I want to replace static id with the value that comes from the selected product. In my Product file I have redirection to page with product but I don't know how I can pass the ID.
onClick={() => { navigate(`/products/${product?.id}`)}}
Any help would be appreciated.
CodePudding user response:
onClick={ () => Navegar(id) }
function Navegar(id) {
navigate('/products/id)
}
CodePudding user response:
so you already have the id with this
navigate(`/products/${product?.id}`)
just in Product component you can access id with
const { id } = useParams();
if you need to pass extra data you can try:
navigate(`/product/${product?.id}`, { state: { someExtradata }};
that you can access state in the component with :
const { state } = useLocation();
CodePudding user response:
The code you've provided appears to pass the id
value in the path. It seems your question more about getting the Product
component to have the correct id
prop passed to it.
Given: path is "/products/:id"
Options to access the id
param:
Use the
useParams
hook inProduct
to read theid
route path param. This only works ifProduct
is a function component.import { useParams } from 'react-router-dom'; ... const { id } = useParams();
...
<Route path={ROUTES.product} element={<Product />} />
Use a wrapper component to use the
useParams
hook and inject theid
value as a prop. This is useful ifProduct
is not a function component.import { useParams } from 'react-router-dom'; const ProductWrapper = () = { const { id } = useParams(); return <Product id={id} /> };
...
<Route path={ROUTES.product} element={<ProductWrapper />} />
Create a custom
withRouter
Higher Order Component to use theuseParams
hook and inject aparams
prop.import { useParams, ...other hooks... } from 'react-router-dom'; const withRouter = Component => props => { const params = useParams(); ... other hooks... return ( <Component {...props} params={params} ... other hooks ... /> ); };
...
Wrap
Product
withwithRouter
HOC and accessid
param fromprops.params
props.params.id // or this.props.params ... export default withRouter(Product);
...
<Route path={ROUTES.product} element={<Product />} />