Multiple parameters with React Router v6
In this article, we will show you how to implement multiple parameters with React Router v6. Refer to the article Multiple parameters with React Router if you are working with React Router version 5.
In this example, we’ll pass two optional parameters in the URL using React Router v6.
We'll continue to use the previous article. For more information, please see the earlier post Nested routes using React Router v6.
Demo Application
Output - Multiple parameters with React Router v6 - Clue Mediator
Steps to add multiple parameters with React Router v6
1. Project structure
Refer to the following project structure for multiple parameters.
-
multi-params-react-router-v6
-
node_modules
-
public
- index.html
-
src
- About.js
- App.js
- Contact.js
- ContactLocation.js
- Demo.js
- Home.js
- index.css
- index.js
- NotFound.js
-
package-lock.json
-
package.json
-
README.md
-
If you compare it to the previous post, you will see that the `src` directory now has an extra file called `Demo.js`.
2. Package version
In this example, we have used the following packages.
react
^18.2.0
react-router-dom
^6.3.0
3. Add multiple parameters
First, we’ll create a `Demo` component to render with multiple parameters.
Demo.js
import React from 'react';
import { useParams } from 'react-router-dom';
const Demo = () => {
const { param1, param2 } = useParams();
return <div>
<h4>Demo</h4>
<p>This is Demo page.</p>
<div>{param1 ? <b>Parameter 1: {param1}</b> : <i>Parameter 1 is optional.</i>}</div>
<div>{param2 ? <b>Parameter 2: {param2}</b> : <i>Parameter 2 is optional.</i>}</div>
</div>
}
export default Demo;
Now, we have to set the routes for the multiple parameters. Let’s add the following routes in the `App.js` file.
App.js
<route path="demo">
<route index="" element="{<Demo">} />
<route path=":param1" element="{<Demo">} />
<route path=":param1/:param2" element="{<Demo">} />
</route>
</route></route></route>
Here, we have set the routes for `param1` & `param2` parameters. Both are optional in the above defination.
4. Output
Run the application and check the output in the browser.
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂