Home > Enterprise >  React Router Navigate pathing
React Router Navigate pathing

Time:05-01

I would like to understand better how the useNavigate works as I'm not really understanding the pattern.

This is my Routes

<BrowserRouter>
      <Routes>
        <Route path="/" element={<Homepage />} />
      </Routes>
      <Routes>
        <Route path="/questionaire" element={<Questionaire />} />
        <Route path="questionaire/1" element={<Question1 />} />
        <Route path="questionaire/2" element={<Question1 />} />
      </Routes>
    </BrowserRouter>

On the Questionaire page I use navigate("1") and it goes into the path "/questionaire/1" - Nice!

Now on question1 I want to go into "/questionaire/2":

  • navigate("2") - leads me into /questionaire/1/2
  • navigate("/2") - leads me into /2
  • navigate("questionare/2") - leads me into /questionaire/1/questionaire/2

How do I make an increment so every question just adds How do I go from questionaire/5 into questionaire/2 using navigate?

I'm using navigate in buttons, should I use LINK? with a button nested in it? Why?

EDIT: doesn't necessarily have to increment the value, but just replace the current number with the one I want - ex question/1 to question/2 or from question/5 to question/3

CodePudding user response:

as i know. (i am noob)

On the Questionaire page I use navigate("1") and it goes into the path "/questionaire/1" - Nice! Now on question1 I want to go into "/questionaire/2": navigate("2") - leads me into /questionaire/1/2

When you use just a number or string, useNav just adding it with / after current path. If you instead of number 2 write 'hi' it navigate you to /hi.

navigate("/2") - leads me into /2.

Its because you wrote absolute path, if before your string in useNav you will add "/", then its meaning "yourhost" "your string". example: Your host is localhost:3000. If you entered '/test' in useNav it will be localhost:3000/test. Or you want add this "/test/2/3" - then it will be localhost:3000/test/2/3.

navigate("questionare/2") - leads me into /questionaire/1/questionaire/2

as i said if you have just string and before it you didnt add /, then its just added after your current path.

CodePudding user response:

Answering you second question:

How do I make an increment so every question just adds How do I go from questionaire/5 into questionaire/2 using navigate?

navigate("questionare/2") - leads me into /questionaire/1/questionaire/2

You can do this using absolute path (e.g: '/questionaire/2') or relative path (e.g: '2'), you can either do this using a Link or programmatically using a useNavigate hook.

const navigate = useNavigate()
const handleClick = () => {
   navigate('2')
   //or
  navigate('/questionaire/2')
} 

Your current code is using relative path adding entire path, which leads to duplicated path as you mentioned.

  • Related