I am trying to dynamically create routes using react-router-dom. The route will depend on the id of a state I have in one of my components. How can I achieve this? App.js:
function App() {
return (
<div className="App">
<Router>
<Route path="/" component={Categories}></Route>
<Route path="/:cat" component={Recipes}></Route>
</Router>
</div>
);
}
Categories.js which I want to get the id (:cat) from - the state categories has an id value:
class Categories extends React.Component {
state = {
categories: []
}
componentDidMount() {
fetch('http://localhost:8000/api/categories/')
.then(response => response.json())
.then(data => {
this.setState({categories: data});
});
}
render() {
return (
);
}
}
I have seen others use useParams but I can't do that since Categories is a class. Thank you for the help.
<Route path="/:cat" component={Recipes} />is all you need to create a dynamic route. Are you really trying to ask a different question, like how to then navigate to a dynamic route? You're correct, theuseParamshook can't be used in a class component, but it also isn't used to generate routes, it gives you the currently matched route'smatch.params. Please clarify what you are trying to do and what, if any, issue is.path="/:cat"handles that. The ":cat" is a "placeholder" for the actual value of the path, i.e. if you navigate to "/4" then in the routematch.params.catwill be"4". Does this make sense? Also,categories = [id=4]isn't valid array syntax.