Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In React-Router-Dom how do I go to another page while also going to an id

I am using React-Router-Dom in one of my projects and am trying to go to another page while also going to an id. I have a

let linkTo = /Countries#Germany
<Link to={linkTo}></Link>

And when I press the Link it only goes to the Countries page and not to the element in the other page with the id of Germany. Is there a way to fix it?

like image 839
Tamir Polyakov Avatar asked Jan 26 '26 19:01

Tamir Polyakov


2 Answers

Are you trying to go to the subsection in the Countries page where there's a Germany section?

If so, there's no way to do this out of the box with React Router, unfortunately, but there's a very easy library that does it.

React Router hash link

The docs explain it, but literally all you do it is:

  1. Add the library and import the Hashlink into your React module.
  2. Replace your components with the -- keep the to prop the same value.
  3. Add the hashlink as the id on the component you're trying to nav to. For ex., add the #Germany id on the Germany component. These ids can be added dynamically if you're using dynamic components.
like image 186
terraforme Avatar answered Jan 29 '26 08:01

terraforme


You need to add the :id to the route definition, then pass the value of the id to the route inside the Link component:

<Route name="route name" path="/:id or param name" component={<component/>} />

Then

<Link to={'/route name/id value'} />

View more ways on the official docs

like image 20
Ali H. Kudeir Avatar answered Jan 29 '26 09:01

Ali H. Kudeir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!