Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading