⚠️ This lesson is retired and might contain outdated information.

React Router: Route Parameters

Joe Maddalone
InstructorJoe Maddalone
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 2 years ago

A router library is no good if we have to hardcode every single route in our application. In this lesson we look at how to access variables in our routes and pass them into our components.

[00:00] In React Router, a route parameter allows us to pass in a portion of our route path as a property of our component that we're going to render at that path. I'm going to create a route here, and its path is going to be /, and now this is going to be my prop that I want to pass in. I want to grab this out of the URL. I'm going to precede this with a colon, and I'm going to say message.

[00:27] Message is the name of the property that I want to pass into my component. I'm going to go ahead and just call my component message. I'm going to make the argument optional by wrapping it in parentheses. This syntax, the parentheses, the colon, is very common amongst many of the routing libraries available.

[00:48] I'm going to go to create our message component. It's going to take in props, and we're going to return a...let's say we're going to have div with an h1. Here's where we're going to output our message properties. The way we get to that is props.params.message. Params is this new property that's passed in by React Router, and it contains any of the arguments that we're looking for in the path.

[01:20] If we don't have that, I'm just going to say hello, and then after the h1, we're going to have a links component. Let's go ahead and create that, links. Here, we're going to return a nav, and then a series of link components. The first one is going to be to /, and we're going to say hello. There, we have no parameter being passed in, so it should just default to hello.

[01:48] We're going to create another. Here, we'll say hi, and one more. Here, we'll say yo and we'll say yo there. Let's save that and try it out. We are on our route path, and we're getting hello. If we go to hi, our path is /hi, and we can see that we're getting that message argument in our component. If we go to yo, we get yo. Hello, again, we get hello.

Tom
Tom
~ 8 years ago

Looks like the new version of React Router changes props.params to props.routeParams

Joel Hooks
Joel Hooks
~ 8 years ago

Looks like the new version of React Router changes props.params to props.routeParams

Thanks for the heads up Tom, we will look into that.

David Weiss
David Weiss
~ 7 years ago

Ouch, my brain hurts! ;-) In react router a route parameter allows us to pass in a portion of our route path as a property of our component that we’re gonna render at that path

Markdown supported.
Become a member to join the discussionEnroll Today