This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    React Router: Route Parameters

    Joe MaddaloneJoe Maddalone

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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.

    Discuss

    Discuss