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

Already subscribed? Sign In

Autoplay

    React Router: Querystring Parameters

    Joe MaddaloneJoe Maddalone

    In this lesson we'll extract props for our component from a querystring in the route url.

    reactReact
    0.14 - 16
    react-routerReact Router
    ^3.0.0
    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 React router allows us to pass in query strings as props to any component that's going to be rendered at a specific route, so here I'm creating a quick component called "page." It's simply going to return a div with an h1. To get at a query string we're going to use props.location, then Query, and then the property that we're looking for on the query. The message will be the query parameter in the URL.

    00:29 If we don't have that, I'm just going to say "hello." We're going to set up our router in our app component. Here's our router. Using the #history, we're just going to set up a single route with a path to forward slash and then the component that'll be rendered there is page.

    00:52 You can see here we're not passing in any route parameters. We're only going to be using query parameters. I'm going to save that and we've got our hello. Here in the URL right before the _k parameter, I'm going to create a parameter called "message," I'm going to say equals below there and then we'll split that up with an &.

    01:15 We get our "hello" there from our query string. We'll go ahead and jump back to our route and now we're going to take a look at how to use the query parameters in a link component. I'm going to create a new function here, component here called "links." We're simply going to return a nav with a link component in here.

    01:40 Rather than using a string in the "to" parameter or property, we're going to pass in an object and we're going to have a key of path name. This is going to represent what our string used to represent. There's our forward slash. Now we're going to pass in a query -- that's another object -- with the key that we want to send along with the query string, and then the value.

    02:02 Here I'm just going to say go and then we're going to drop our links component right here inside of our page component. I forgot to put a little bit of text there, so we'll say "yo."

    02:15 When we click on this, our query string with the parameter of "message" and a value of "yo" is passed into our component.

    Discuss

    Discuss