Languages
[Edit]
EN

React / react-router - router with optional path parameter

3 points
Created by:
Inayah-Alexander
767

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.

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.

❤️💻 🙂

Join