Languages
[Edit]
EN

React / react-router - router with optional path parameter

0 points
Created by:
Inayah-Alexander
497

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

In the example below, we use useParams hook to access the optional path parameter - id 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 ReactDOM from 'react-dom';
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  useParams,
} from 'react-router-dom';

const App = () => {
  return (
    <Router>
      <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>
    </Router>
  );
};

const Child = () => {
  let { id } = useParams();

  return (
    <div>
      <h2>ID: {id}</h2>
    </div>
  );
};

export default App;

You can run this example here.

Related post

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