Home > Software engineering >  Direct to base nested react route
Direct to base nested react route

Time:03-19

I need to have a link that will direct me to the base nested route, for instance I have the URL "app/dashboard" within the dashboard UI I want to have a link the will direct me to the base nested URL which is "app/dashboard". When I use the "/" in the 'to' attribute it directs me to the root base which is "app".

Index.js

<Routes>
    <Route path="/" element={<App />}>
      <Route path="register" element={<Register />} />  
    </Route>
    <Route path="dashboard" element={<Dashboard />}>
      <Route index element={<Home />} />
      <Route path="upload-reciept" element={<UploadReciept />} />
      <Route path="upload-details" element={<UploadDetails />} />
    </Route> 
</Routes>

Dashboard.js

<ul className="space-y-2">
   <li>
      <NavLink to="/" className={({ isActive }) => isActive ? "bg-sky-200 text-sky-700" : "hover:bg-sky-200 hover:text-sky-700"}>
         <HomeIcon className="h-5 w-5 sm:h-6 sm:w-6"/>
         <span>Home</span>
      </NavLink>
   </li>
   <li>
      <NavLink to="upload-reciept"  className={({ isActive }) => isActive ? "bg-sky-200 text-sky-700" : "hover:bg-sky-200 hover:text-sky-700"}>
         <CloudUploadIcon className="h-5 w-5 sm:h-6 sm:w-6"/>    
         <span>Upload reciept</span>
      </NavLink>
   </li>
   <li>
      <NavLink to="upload-details"  className={({ isActive }) => isActive ? "bg-sky-200 text-sky-700" : "hover:bg-sky-200 hover:text-sky-700"}>
         <RefreshIcon className="h-5 w-5 sm:h-6 sm:w-6" />
         <span>Update details</span>
      </NavLink>
   </li>
</ul>

How do I go about directing the "Home" link to "app/dashboard"?

CodePudding user response:

Use "." as the link target to target the current "directory" path "/dashboard". Add the end prop for this link so it's only active when the path ends with the path the link is targeting, i.e. "/dashboard".

<NavLink
  to="."
  end // <-- to match path "/dashboard"
  className={({ isActive }) =>
    isActive
      ? "bg-sky-200 text-sky-700"
      : "hover:bg-sky-200 hover:text-sky-700"
  }
>
  <HomeIcon className="h-5 w-5 sm:h-6 sm:w-6" />
  <span>Home</span>
</NavLink>

Edit direct-to-base-nested-react-route

CodePudding user response:

you didnt define /app route you have to way at first step you can define nested Route like this


    <Routes>
         <Route to="/app" element={<App/>}>
         <Route to="dashboard" element={<Dashboard/>}>
              //other <Route/>
         </Route>
       </Route>
    <Routes>

or you can use the old way (before v6) and you even can define route as a hard code and define exact Route to react like : <Route to="/where/ever/you/want" {...props} /> for other thing check the document of react-router-dom its very easy goodluck dude!!!

  • Related