this is my App.js Component
<Routes>
<Route path='/products/:id' element={<ProductDetails/>} />
// other <Route />
</Routes>
and this is my ProductDetails Component
const ProductDetails = (props) => {
const id = props.match.params.id
return (
<div>
<h1> {id} </h1>
</div>
);
};
but i got this error = TypeError: Cannot read properties of undefined (reading 'params')
what should I do??
CodePudding user response:
if you are using the react-router-dom
package you can access the URL parameters using the useParams hook.
import { useParams } from "react-router-dom";
const ProductDetails = (props) => {
const { id } = useParams()
return (
<div>
<h1> {id} </h1>
</div>
);
};
official documentation: https://v5.reactrouter.com/web/api/Hooks/useparams
CodePudding user response:
You need to pass the props
like this
<Routes>
<Route path='/products/:id' render={(props) => <ProductDetails {...props}/>} />
// other <Route />
</Routes>
Or you can use withRouter
HOF to get the props
import { withRouter } from "react-router";
const ProductDetails = (props) => {
const id = props.match.params.id
return (
<div>
<h1> {id} </h1>
</div>
);
};
export default withRouter(ProductDetails);