Tamir Polyakov
Tamir Polyakov

Reputation: 164

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?

Upvotes: 3

Views: 1461

Answers (2)

Ali H. Kudeir
Ali H. Kudeir

Reputation: 1054

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

Upvotes: 0

terraforme
terraforme

Reputation: 458

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.

Upvotes: 2

Related Questions