How to create a dynamic Link to attribute in React-Router 2.5

20,854

Solution 1

You are doing it right! :)

As you can see in the docs, this is the correct way to pass the to prop:

https://github.com/reactjs/react-router/blob/v2.5.2/docs/API.md#link

In previous React Router versions, there was a prop called params, where you would pass all your route params.

https://github.com/ReactTraining/react-router/blob/v0.13.6/doc/03%20Components/Link.md#params

But I think the React Router team decided to keep things simple, so you decide how you will build your routes. Also, using ES6 templates fit very well with that.

Solution 2

In the API-documentation of react-router it is done in the exact same way:

// change the activeClassName
<Link to={`/users/${user.id}`} activeClassName="current">{user.name}</Link>

Reference: https://github.com/reactjs/react-router/blob/master/docs/API.md#link

Share:
20,854
Matthew Nichols
Author by

Matthew Nichols

I am a passionate full-stack web developer living in Gibraltar. My current tech passions are ES 201X/Typescript/Vue, NodeJS and a little Rust. I am joyously married to Mary Camacho who to my delight has a stackoverflow account and is, among her other areas of genius, an coder. We own our own business, JoyaSolutions which keeps me very busy. In my spare time I have been learning Blender and delighting in things like nand2tetris.

Updated on March 16, 2020

Comments

  • Matthew Nichols
    Matthew Nichols about 4 years

    (Disclaimer: I am new to React and React-Router, so this may be obvious to someone with more familiarity)

    I am creating a simple project with React-Router 2.5.2 with ES6 and I have a working solution but it feels like it may not be the "React Router way". I have this Route:

    <Route path="lists/:listId" component={List}/>
    

    and elsewhere I have a Link:

    <Link to={`/lists/${props.list._id}`}>{props.list.name}</Link>
    

    Is this the preferred way to compose a "to" attribute that passes dynamic content? Or am I fundamentally misunderstanding React Router?

  • Chandresh
    Chandresh about 6 years
  • William Martins
    William Martins about 6 years
    Just updated the answer with the correct link (github.com/ReactTraining/react-router/blob/v0.13.6/doc/…) @Chandresh