React Router: Querystring Parameters

Joe Maddalone
InstructorJoe Maddalone

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 3 years ago

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

[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.

~ 6 years ago

Great job on the set of lectures. I just want to know is it possible to access the Link functionality for form and input, by that I mean can one pass the query from a form input field and have it change the url rather than have a button to click.