Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

(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?

like image 970
Matthew Nichols Avatar asked Jul 08 '16 14:07

Matthew Nichols


People also ask

How to add react router in react app?

React Router is the most popular solution. To add React Router in your application, run this in the terminal from the root directory of the application: Note: This tutorial uses React Router v6.

How to set up dynamic routing in react?

Setting Up Dynamic Routing in React 1 Setting Up Routing. Let’s start by setting up some routing. ... 2 Linking to the Product Component. We’re just about ready to work on the Product component. ... 3 Creating the Product Component. So let’s create a file called Product.js. ... 4 Rendering the Product Page. ... 5 Conclusion. ... 6 Final Code

What is the use of link component of react?

This is the use of the Link component of React. The path, written in the ‘to’ property of Link matches with the ‘path’ property of Route. You can go through React-Link for more examples.

How to navigate around react-router-DOM using Link and navlink?

The <Link> and <NavLink> are the components provided by react-router-dom to navigate around the react application. Generally, we use anchor tags for this purpose while navigating.


2 Answers

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

like image 64
Johannes Reuter Avatar answered Oct 22 '22 01:10

Johannes Reuter


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.

like image 40
William Martins Avatar answered Oct 22 '22 01:10

William Martins