reactjsroutesreact-router-domdynamic-routing

How to set dynamic URL parameters to a variable value with react-router-dom


I looked quite a bit online for this but didnt seem to find the right answer to my question. How do I change a part of my URL to a value from for example UserInput.

I am using react-router-dom v6 and react 18.2

I tried to use UseParams but it didnt work as wished. Also I tried redirect and useHistory but it didnt lead to the wished result, perhaps i used them wrong in my scenario

This is what i have so far:

App.js


let persID = useContext(NumContext); // i use this since the Original value lays in another Script

return (


<Link to="/schedule/mySchedule/:persID" ><p className="NavText">My Timetable</p></Link> {/* persID is the dynamic URL part that should be replaced with a value out of varaible */}


<Route path="/schedule/mySchedule/:persID" element={<MySchedule />} />


)

What i want is that if the value of the varable is 2 it leads to the URL /schedule/mySchedule/2

I've seen people do this but they had to replace the part of the dynamic route manually

I am Thankful for any advice or leads


Solution

  • What i want is that if the value of the varable is 2 it leads to the URL /schedule/mySchedule/2

    You could use template literal to include the persID param within the link.

    <Link to={`/schedule/mySchedule/${persID}`} />
    

    More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals