Categories
React Answers

How to Map Multiple Path Names to the Same Component in React Router v5?

Spread the love

Sometimes, we want to map multiple path names to the same component in React Router v5.

In this article, we’ll look at how to map multiple path names to the same component in React Router v5.

Map Multiple Path Names to the Same Component in React Router v5

To map multiple path names to the same component in React Router v5, we can add a | symbol between the paths that we want to match.

For instance, we write:

import React from "react";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";

const Child = () => {
  return (
    <div>
      <p>foo</p>
    </div>
  );
};

export default function App() {
  return (
    <Router>
      <div>
        <ul>
          <li>
            <Link to="/foo">foo</Link>
          </li>
          <li>
            <Link to="/bar">bar</Link>
          </li>
        </ul>

        <Switch>
          <Route path="/(foo|bar)/" children={<Child />} />
        </Switch>
      </div>
    </Router>
  );
}

We create the Child component which we map either to the foo path or the bar path with '/(foo|bar)/'.

children is set to Child so it’ll be rendered.

And we have one Link that goes to the foo path and another that goes to bar.

Therefore, when we click on either link, we see ‘foo’ displayed.

Conclusion

To map multiple path names to the same component in React Router v5, we can add a | symbol between the paths that we want to match.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *