Next lesson playing in 5 seconds

Cancel
  • Overview
  • Transcript

4.9 Challenge: Route Parameters

You can use the props.routeParams to get parameters from the route. Your challenge is to create a route that will get the name from routes like /hello/[name] and display a welcome message in a new component.

Related Links

4.9 Challenge: Route Parameters

Challenge 11 is our last challenge involving routers. In this lesson, we have two links, one going to /hello/Kari and one going to /hello/Adam, and what we wanna do is make both these links render the same component. So, we need some way to have a parameter in a route that can be different things. If you wanna figure this out on your own, go ahead and fork this CodePen. You can find the link to this underneath the video, of course, and if you'd like to do that, go ahead and pause now because I am going to show you my solution. As you can see, right now if we were to click carry Or Hello Adam. We have nothing here because we have a road not found component being rendered in our catch all route. So we need to put some route in the middle. So of course, this is going to be a route with a path, and the path is going to be / Hello and then slash colon name. And when we prefix part of our route here with a colon that means this is a variable that can be anything in this path. We can say that and then we need to Having a component here, and let's create a component that we're going to call hello. And let's create our hello component. So we'll put that right here, const Hello. And this is course is going to take some props. And we have a note up here which actually helps us out. You can use props.roteParams to get the parameters from a route and this has changed in the latest version of React. It's now Props.match.params but it's the same principle applies really. So here we can get our h1 and we'll say Hello and then in here we can say props.routeParams and then we can just use whatever name we called our token in the route. So in this case that's name. And that's our hello component. So now if I click, Say hello to Kari. We get, Hello Kari. If I click, Say hello to Adam, we get Hello Adam. And we can actually edit this in our little location bar here. So I can say, Andrew for example. Or we can say. Tuts+, notice that if we completely take off the name we get nothing here because that doesn't match one of our routes. Our route requires a name after that trailing slash. So as long as we give it anything there we will match that route. Okay, so there we go we have finished our route parameters challenge and you have successfully created a route that can match A pattern of route instead of a specific hard code of route. Good job!

Back to the top