React router v6 : update url param in Link

Viewed 38

i'm learning react and i'm facing something I don't understand about the Link component.

I'm making a simple survey with two buttons that links to previous and next question. Here is the architecture of my app :

ReactDOM.render(
   <React.StrictMode>
      <BrowserRouter>
         <Header />
         <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/survey/:questionNumber" element={<Survey />} />
            <Route path="/results" element={<Results />} />
            <Route path="*" element={<Error />} />
         </Routes>
      </BrowserRouter>
   </React.StrictMode>,
   document.getElementById("root")
);

My component Survey look like this :

import { useParams, Link } from "react-router-dom";

function Survey() {
   const { questionNumber } = useParams();
   let questionNumberInt = Number(questionNumber);

   const prevQuestionNumber =
      questionNumberInt === 1 ? null : questionNumberInt - 1;
   const nextQuestionNumber = questionNumberInt + 1;

   return (
      <div>
         <h1>Questionnaire </h1>
         <h2>Question {questionNumber} </h2>

         {questionNumberInt === 1 ? null : (
            <Link to={prevQuestionNumber}>Précédent</Link>
         )}

         {questionNumberInt === 10 ? (
            <Link to="/results">Résultats</Link>
         ) : (
            <Link to={nextQuestionNumber}>Suivant</Link>
         )}
      </div>
   );
}

export default Survey;

With this code I can observe (let assume that we are currently at page "/survey/2") that

<Link to={prevQuestionNumber}>Précédent</Link>

is tranformed in the HTML file into

<a href="/survey/2">Précédent</a>

(same for the next link which refers to "/survey/2"). So for whatever reason my links aren't working.

I've found that I can make it works by writing

<Link to={'/survey/${prevQuestionNumber}'}>Précédent</Link>

and then I actually obtain prev and next links thats refers to "/survey/1" and "/survey/3".

But I'm annoyed by having to write the full url, as react router v6 introduced relative routes, so I want to use that. Indeed, I've found that if I write

<a href={prevQuestionNumber}>Précédent</a>

directly in my code, instead of the using Link, then it works perfectly and I'm correctly redirected when clicking my prev and next links.

So I don't know how to recreate this using Link and why <Link to={prevQuestionNumber}>Précédent</Link> doesn't works, can someone explain me please ?

1 Answers

Hey Welcome to Stack Overflow,

So the reason why below code is working

<Link to={'/survey/${prevQuestionNumber}'}>Précédent</Link>

If you see your routes, you have only one route which accept dynamic path and that is

<Route path="/survey/:questionNumber" element={<Survey />} />

On the other hand, when you are trying <Link to={prevQuestionNumber}>Précédent</Link> it does not find relavant path in the routes and gives error page or no page or blank page.

Related