I have been trying to display the product name in the ProductScreen
component by passing the ID of the image.
My router configuration looks like this:
const router = createBrowserRouter(
createRoutesFromElements(
<Route>
<Route path='/' element={<HomeScreen />} exact />
<Route path='/cart' element={<ProductScreen />} />
<Route path='/product/:id' element={<ProductScreen />} />
</Route>
)
)
The id
is then used to retrieve the product name from product.js
This is to be displayed inside the productscreen.js
import products from '../products'
function ProductScreen({match}) {
const product = products.find((p) => p._id == match.params.id)
return (
<div>
{product.name}
</div>
)
}
How do I do this?
react-router-dom@6
removed route props, use the useParams
hook in the routed component.
Be aware also that Array.prototype.find
does return undefined if/when no element in the array is matched. The UI could should check first that a result was found.
The route path parameters are always a string type, so you will also want to use a type-safe comparison to your data. I suggest converting and using string comparisons and use a strict equality check.
Example:
import { useParams } from 'react-router-dom';
import products from '../products';
function ProductScreen() {
const { id } = useParams();
const product = products.find((p) => String(p._id) === id);
if (!product) {
return <div>No product.</div>
}
return (
<div>
{product.name}
</div>
);
}