React / react-router - router with optional path parameter

3 points
Created by:

In this article, we would like to show you how to use react-router with optional path parameter in React.

Quick solution:

  <Route path="/:optionalParameter?" children={<Child />} />

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 (
      <h2>ID: {id}</h2>

const App = () => {
  return (
          <li><Link to="/home">Home</Link></li>
          <li><Link to="/gallery">Gallery</Link></li>
          <li><Link to="/about">About</Link></li>
          <Route path="/:id?" children={<Child />} />

export default App;

You can run this example here.

Related post

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

React - react-router

Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂