In this quick post we will be covering how to use React Router with an optional path parameter so you can solve this issue quickly and without having to look any further!
As with all my Quick Fix Series of posts, you will first find the problem described and then the solution just below.
Let’s get stuck in!
The Problem - React router with optional path parameters
Generally speaking if you are using path parameters in React Router which are defined with a colon in the path string, you shouldn’t need to have optional parameters.
If a parameter is optional it is probably going to be better suited as a GET parameter instead of a path parameter because optional path parameters will get pretty confusing, especially if someone working on them lacks context.
Here is an example of a non-optional path parameter:
<BrowserRouter>
<Switch>
<Route path="/example/:someParam" component={ExampleComponent} />
</Switch>
</BrowserRouter>
There are times when using a GET parameter is not as easy as using an optional path parameter though, and one of these times could be when you are trying to render a specific component for a given route regardless of if the parameter is there or not.
The Solution - Using React Router with an optional path parameter.
As I have mentioned before, I believe that if you need an optional parameter in most cases you should probably be making use of a GET parameter instead of an optional path parameter.
With that said, let’s take a look at how you can use an optional path parameter in React Router.
To add in an optional path parameter in React Router, you just need to add a ?
to the end of the parameter to signify that it is optional.
Here is an example:
<BrowserRouter>
<Switch>
<Route path="/example/:someParam?" component={ExampleComponent} />
</Switch>
</BrowserRouter>
If you were using a GET parameter instead you wouldn’t need to add in any path parameter so instead your React Router would look like the following:
<BrowserRouter>
<Switch>
<Route path="/example" component={ExampleComponent} />
</Switch>
</BrowserRouter>
And then in your component you could access the GET parameters using the location.search prop that is passed in by React Router.
Let’s use the above example and assume that a request is being made with the following GET parameter /example?name=John
Here is how we could then use it in our component:
export default function ExampleComponent({ location }) {
const name = new URLSearchParams(location.search).get("name")
return <h1> Hello {name} </h1>
}
Summary
There we have the quick fix to how to use React Router with an optional path parameter, if you want more like this be sure to check out some of my other posts!