i have been looking into some examples on stack overflow for defining optional query params in react-router and finally found out that it can be done like
JavaScript
x
8
1
{
2
path: '/forms/simulacao/:journeyId?',
3
exact: true,
4
name: 'Home',
5
component: Home,
6
authRequired: true
7
}
8
so at next step i want to retrive the query param that is “journyeId” if it is there, so i tried with
JavaScript
1
3
1
const history=useHistory()
2
console.log(history.location)
3
but that doesn’t seems to work, what should be the workaround for this ??
“react-router”: “^5.1.2”, “react-router-dom”: “^5.1.2”,
Advertisement
Answer
there is a hook for this: useParams from react-router-dom
JavaScript
1
2
1
<Route path="/item/:id" component={NewsPage} />
2
After that, in NewsPage component I will be able to grab an ID from route like this:
JavaScript
1
3
1
const params = useParams()
2
fetchNews(params.id).then(data => setNews(data))
3
And so on