skip to Main Content

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


  1. If you want to go back to the previous page in react-router-dom v6 then you can use useNavigate.

    import { useNavigate } from 'react-router-dom'
    
    const Component = () => {
       const navigate = useNavigatge()
    
       return (
          <button onClick={() => navigate(-1)}>Go back</button>
       )
    }
    

    You can also change the number inside navigate to -2 if you want to go back two pages and so on.

    Login or Signup to reply.
  2. 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:

    <Link to="../">Parent category</Link>
    
    // OR in some cases
    
    <Link to=".." relative="path">Parent category</Link>
    

    Maybe take a look also at the useNavigate hook (React-dom doc)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search