'Render same component for 3 routes

I want my react router to return component only when URL matches either of those 3 paths exactly and return an error when it doesn't. How can I shorten this?

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Table entries={posts} />} />
        <Route path="/evens" element={<Table entries={posts} />} />
        <Route path="/odds" element={<Table entries={posts} />} />
        <Route ??? element={<ErrorPage />} />
      </Routes>
    </BrowserRouter>
  );


Solution 1:[1]

RRDv6 routes take only a string path prop. If you need to render the same component on multiple paths you need to render a Route for each.

To make the code a little more DRY you could try mapping the routes from an array of paths.

Example:

return (
  <BrowserRouter>
    <Routes>
      {["/", "/evens", "/odds"].map(path => (
        <Route
          key={path}
          path={path}
          element={<Table entries={posts} />}
        />
      )}
      <Route path="*" element={<ErrorPage />} />
    </Routes>
  </BrowserRouter>
);

Now whether or not this is more readable or maintainable is likely up for debate/opinion. It is less repetitive though.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Drew Reese