2

I have a very simple page app, the index route does not work on it.

import { Routes, Route, Outlet } from 'react-router-dom';
import Home from './routes/home/home.component.jsx'
import Heading from './components/Heading';

function Header () {
  return (
    <>
      <Heading />
      <Outlet />
    </>

  )
}

function App() {
  return (
    <Routes>
      <Route path='/' element={<Header />} >
        <Route index path='home' element={<Home />} />
      </Route>
    </Routes>
  );
}

export default App;

This is what gets shown on default, only the navbar with no home index element: enter image description here

My question is why is that happening and how to fix this when my code is basically non existent and I can't see where I made the mistake

Thanks!

AoXNeR
  • 47
  • 6
  • I don't think it does, I have the outlet where it should render, and it succeeds to render if the route is '/home' but on route '/' it's not rendering the index route. – AoXNeR Jul 24 '22 at 16:12
  • 1
    https://stackoverflow.com/questions/70228775/how-to-setup-index-route-on-nested-parent-route-in-react-router-v6 – shet_tayyy Jul 24 '22 at 16:26
  • I noticed just now that it was you that proposed an edit to my answer. I rejected the edit adding the `BrowserRouter` as it wasn't included in the code snippet in the original post. I'd assumed the router component was just higher up the ReactTree. Is there also some issue with a missing router in your actual code? – Drew Reese Jul 24 '22 at 22:26

1 Answers1

7

While the index and path props are both optional, don't use both at the same time. The path="home" prop is overriding the index prop.

If you want the Home component to render on both "/" and "/home" then you'll need two routes for this. One specified as the index route and renders on the parent route's "/" path, and the other to render on the nested "/home" path.

Example:

function App() {
  return (
    <Routes>
      <Route path='/' element={<Header />} >
        <Route index element={<Home />} />
        <Route path='home' element={<Home />} />
      </Route>
    </Routes>
  );
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181