Home > Mobile >  React router v6 - Navigating from parent route to nested route without showing the parent route
React router v6 - Navigating from parent route to nested route without showing the parent route

Time:06-27

I'm trying to use nested routes for this code here in my Router.js:

return (
<Routes>
  <Route path="" element={<Home />} />
  <Route path="/DriverPage/*"  element={<DriverPage />}>
      <Route path="DriverSignUp" element={<DriverSignUp />}/>
      <Route path="DriverLogin" element={<DriverLogIn />} />
  </Route>
  <Route path="/PassengerPage/*" element={<PassengerPage />} />
</Routes>

);

And this is the code in the DriverPage.js component which is the parent route:

return (
<>     
  <div className="driver-auth">
    <button onClick={ ()=>navigate("DriverSignUp",{replace:true}) }> Sign up </button>
    <button onClick={ ()=>navigate("DriverLogin",{replace:true}) }> Sign in </button>
  </div>
  <Outlet />
</>

The problem is that I want to replace the parent component with the nested component when the buttons are clicked, because I don't want the parent to keep showing.

That's why I've tried to use navigate("DriverLogin",{replace:true}) but it's not helping and I see both the parent and the child route when clicking.

I think It's because of the /* I have in the parent route path, which means that it matches even if just the begining matches.

So, is there any solution for this with still using nested routes or should I not use the nesting?

And one more question is: Why isn't the replace working ?

Thanks!

CodePudding user response:

If you want to view this code example then checkout my sandbox

This is the default behavior of React Router dom

You can get that result in 2 ways

**1. you can define those routes individual **

    <Routes>
      <Route index element={<Home />} />
      <Route path="DriverPage" element={<DriverPage />}/>
      <Route path="DriverPage/DriverSignUp" element={<DriverSignUp />}/>
      <Route path="DriverPage/DriverLogin" element={<DriverLogIn />} />
    </Routes>

**2. Define the nested routes like this **

 <Routes>
  <Route index element={<Home />} />
  <Route path="DriverPage/*" element={<DriverPage />}/>
</Routes>

Parent component

function DriverPage(){
 <Routes>
   <Route index element={your parent code} /> 
   //your parent content only visible if path is /Driverpage.
   <Route path="DriverSignUp" element={<DriverSignUp/>}/> 
   <Route path="DriverSignIn" element={<DriverSignIn/>}/>
 </Routes>
}
export default <DriverPage/>;
  • Related