URL Parameters with React Router

Today we will show you how to set URL parameters with React Router. Major use of URL parameters routing is to render the same component based on its dynamic url.

We are going to continue with the previous example. So refer the previous article Routing in React JS.

The complete guide of Routing in ReactJS

Key points for URL Parameters with React Router

  1. Why we need URL Parameters
  2. Add route for Not Found page
  3. Implement URL Parameters with Example
  4. Output

1. Why we need URL Parameters

As I mentioned previously, To render the same react component based on given dynamic URL like If you have a list of users and you want to display the user details by Id (www.xyz.com/user/1, www.xyz.com/user/2, etc) then URL Parameters is used.

2. Add route for Not Found page

Before we jump on URL Parameters, I want to let you know how to set Not Found page via react router. For that can you please refer previous article. I am going to continue with it.

We need to create Not Found component to load when URL will not match with listed routes.

Notfound.js

We will add this component route at the end of all of the listed routes. Now this is how your updated index.js file looks.

index.js

Let’s check it by manually entering wrong path like http://localhost:3000/abc.

Output - Page Not Found - Clue Mediator
Output – Page Not Found – Clue Mediator

3. Implement URL Parameters with Example

Now simply we need to update index.js file to handle the URL params. Following command will be used for that.

Use below command if you want to set parameter as optional. (For React Router v4 and above)

For React Router v1, v2 and v3

index.js

Use below command to get the url parameters

So your About.js file will look like the following

About.js

4. Output

Output - URL Parameters with React Router - Clue Mediator
Output – URL Parameters with React Router – Clue Mediator

Demo & Source Code

Github Repository
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

4 Responses

  1. Monique says:

    I followed this to a T and get this error:

    Uncaught TypeError: Cannot destructure property ‘params’ of ‘this.props.match’ as it is undefined.

    • Clue Mediator says:

      I don’t think the routing props are found in your component. You have to wrap your component with withRouter or pass the routing props from the parent component.

      Please watch the attached video in the article for more information.

  2. Shinde says:

    I am using Laravel with reactjs, and I have to define react routes in laravel route and react app.js. How to use optional parameter which calls same componenet

    • Clue Mediator says:

      Hi Shinde,
      We have explained the optional parameter in the third point. You can also check the video for more understanding.

Leave a Reply

Your email address will not be published. Required fields are marked *