Home > Back-end >  Nesting routes in react dom v 6 doesn't open the nested component
Nesting routes in react dom v 6 doesn't open the nested component

Time:07-10

I am new to React and I am trying to nest my route team-members under profile so I can reach it like profile/team-members. But the way I am doing it now both ways open profile component content.

import React from "react";
import {BrowserRouter, Routes, Route} from "react-router-dom";
import Home from "./Pages/Home/Home";
import Registration from "./Pages/Registration/Registration";
import Profile from "./Pages/Profile/Profile";
import TeamMembers from "./Pages/TeamMembers/TeamMembers";

const App = () => {
  return(
      <BrowserRouter>
        <Routes>
            <Route index element={<Home />} />
            <Route path="registration" element={<Registration />} />
            <Route path="profile" element={<Profile />} >
                <Route path="team-members" element={<TeamMembers />}/>
            </Route>
        </Routes>
      </BrowserRouter>
  )
}

export default App;

I am looking it at the react dom documentation but still doesn't manage to make it work.

CodePudding user response:

Please try the following:

import {BrowserRouter, Routes, Route} from "react-router-dom";
import Home from "./Pages/Home/Home";
import Registration from "./Pages/Registration/Registration";
import Profile from "./Pages/Profile/Profile";
import TeamMembers from "./Pages/TeamMembers/TeamMembers";

const App = () => {
  return(
      <BrowserRouter>
        <Routes>
            <Route index element={<Home />} />
            <Route path="registration" element={<Registration />} />
            <Route path="profile" >
                <Route index element={<Profile />}>
                <Route path="team-members" element={<TeamMembers />}/>
            </Route>
        </Routes>
      </BrowserRouter>
  )
}

export default App;

Instead of providing the element for the parent route, try providing an index element for the parent, and child routes as usual.

  • Related