Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    React Router: Route Parameters

    0.14 - 16
    react-routerReact Router

    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.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    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.

    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.

    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.

    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.

    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.