EN
React / react-router - router with optional path parameter
3
points
In this article, we would like to show you how to use react-router
with optional path parameter in React.
Quick solution:
<Switch>
<Route path="/:optionalParameter?" children={<Child />} />
</Switch>
Note: use
const { optionalParameter } = useParams()
to access optional parameter in the<Child>
component.
Practical example
In the example below, we use useParams
hook to access the optional id
path parameter, and display it inside <Child>
component.
The unordered list has been created to show example optional parameters, but you can also insert any word as an optional parameter directly in the address bar after starting the application.
Practical example:
import React from 'react';
import { BrowserRouter, Switch, Route, Link, useParams } from 'react-router-dom';
const Child = () => {
const { id } = useParams();
return (
<div>
<h2>ID: {id}</h2>
</div>
);
};
const App = () => {
return (
<BrowserRouter>
<div>
<ul>
<li><Link to="/home">Home</Link></li>
<li><Link to="/gallery">Gallery</Link></li>
<li><Link to="/about">About</Link></li>
</ul>
<Switch>
<Route path="/:id?" children={<Child />} />
</Switch>
</div>
</BrowserRouter>
);
};
export default App;
You can run this example here.