Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

having multiple paths to the same component in react-router-dom v6

i'm trying to have multiple paths/routes in react router v6 to render the same component

using previous versions of react router dom i could just do this and it would work:

<Route exact path={["/", "/home"]}>
     <Home />
</Route>

<Route exact path={"/" | "/home"}>
     <Home />
</Route>

now using v6 i'm trying the same thing but it doesn't work

<Route exact path={["/","/home"]} element={<Homepage />} />

how should i go about this? what changed exactly for it not to work?

full code of App.js where i do the routing

import React from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom'
import Navbar from './components/Navbar';
import Footer from './components/Footer';
import Contact from './components/Contact';
import Homepage from './components/Homepage';
import Projects from './components/Projects'

function App() {
  return (<Router>
    <Navbar />
      <Routes>
        <Route exact path={["/","/home"]} element={<Homepage />} />
        <Route exact path="/contact" element={<Contact/>} />
        <Route exact path="/projects" element={<Projects />} />
      </Routes>
    <Footer />
  </Router>);
}

export default App;

like image 785
M.KH Avatar asked Feb 02 '26 16:02

M.KH


1 Answers

Probably not a good idea to be repeating the code as the accepted answer suggests, easy to break when the call to the components to load changes.

Just map over the array to create the routes:

 {["/", "/home"].map((path, index) => {
        return (
          <Route path={path} element={
              <PageWrapper>
                <Home />
              </PageWrapper>
            }
            key={index}
          />
        );
      })}
like image 61
Rich - enzedonline Avatar answered Feb 05 '26 06:02

Rich - enzedonline



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!