(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?
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.
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
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With