Sometimes, we want to add optional path parameter with React Router v5.
In this article, we’ll look at how to add optional path parameter with React Router v5.
Add Optional Path Parameter with React Router v5
To add optional path parameter with React Router v5, we can add a ? after the route parameter placeholder.
For instance, we write:
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link,
useParams
} from "react-router-dom";
const Child = () => {
const { id, slug } = useParams();
return (
<div>
<h3>ID: {id}</h3>
<h3>slug: {slug}</h3>
</div>
);
};
export default function App() {
return (
<Router>
<div>
<h2>Accounts</h2>
<ul>
<li>
<Link to="/1/foo">foo</Link>
</li>
<li>
<Link to="/1">bar</Link>
</li>
</ul>
<Switch>
<Route path="/:id/:slug?" children={<Child />} />
</Switch>
</div>
</Router>
);
}
We have the Route
component that has the path
prop set to '/:id/:slug?'
.
And we make the slug
parameter optional by adding the ?
after it.
Also, we added links with the path set to a path with and without the second parameter respectively.
In the Child
component, we use the useParams
hook to get the value of both route parameters.
When we click in the foo link, we see that both id
and slug
have values.
And when we click on the bar link, we see only id
is set.
We set the children
prop to the Child
component so that it’s rendered when we click on the links.
Conclusion
To add optional path parameter with React Router v5, we can add a ? after the route parameter placeholder.