I am trying to implement a routing for my react project. No problem for the react router dom, but I am wondering how manage deep routing page’s id, in order to be able to go back to previous pages.
Until now I have implemented useLocation
and also useParams
but I could not figure it out the proper way.
In my case I have 3 level pages "Main Category –> Category –> Sub category ".
Each category has multiple sub categories, so ID has to be dynamic.
The problem is, when I am in "Sub category" and I go back, react does not know which "Category" i came from.
Should I pass the "category ID" until the sub category page?
It is better use useLocation
, useParams
or Redux
? Or maybe you have others better solutions…
`const location = useLocation();
const catName = location.state?.name;
const catID = location.state?.id;`
<BackArrow to={`/catPage/${catID}`} title={catName}/>
2
Answers
If you want to go back to the previous page in
react-router-dom v6
then you can useuseNavigate
.You can also change the number inside
navigate
to -2 if you want to go back two pages and so on.Assuming your routing structure is made out of nested routes, you could use a relative path using react-router-dom’s
Link
(Source) like so:Maybe take a look also at the
useNavigate
hook (React-dom doc)