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
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.
3. Add multiple parameters
First, we’ll create a Demo
component to render with multiple parameters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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.
1 2 3 4 5 | <Route path="demo"> <Route index element={<Demo />} /> <Route path=":param1" element={<Demo />} /> <Route path=":param1/:param2" element={<Demo />} /> </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..!! 🙂