Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading