URL Parameters with React Router v6

In this article, we’ll show you how to set URL parameters with React Router v6. In the previous article, we have explained how to add URL parameters in React Router version 5.

Here, we’ll create an example using React Hooks.

Demo Application

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

Steps to add URL Parameters with React Router v6

  1. Project structure
  2. Setup the React project
  3. Add dependencies
  4. Add URL parameters
  5. Add support for Optional parameters
  6. Implement a Not Found (404) Route
  7. Output

1. Project structure

In this example, we’ll refer the following project structure for parameters routing using React Router version6.

  • url-params-react-router-v6
    • node_modules
    • public
      • index.html
    • src
      • About.js
      • App.js
      • Contact.js
      • Home.js
      • index.css
      • index.js
      • NotFound.js
    • package-lock.json
    • package.json
    • README.md

2. Setup the React project

To setup the React project, use the create-react-app NPM package. Run the following command.

Now, we’ll install the react-router-dom by running the following command.

Once the package has been installed, you can see the following versions of react and react-router-dom by looking at the dependencies versions in the package.json file.

react
^18.2.0
react-router-dom
^6.3.0

4. Add URL parameters

Your routes may be defined as shown below to add the URL parameters.

We have to use the useParams hook to access the URL parameter in the component.

5. Add support for Optional parameters

We need to define the routes as shown below in order to provide optional parameters.

6. Implement a Not Found (404) Route

We must specify the route path as a * as follows in order to add a not found route.

7. Output

Let’s put everything in place and check out the result.

App.js
Home.js
Contact.js
About.js
NotFound.js

I hope you find this article helpful.
Thank you for reading. Happy Coding..!!

Demo & Source Code

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

You may also like...

Leave a Reply

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