I have a fairly simple routing setup in React (TypeScript). I have a Header and a Footer that I always want to display. A home component that displays my frontpage content. The part that bothers me a bit is the projects section. I have a seperate page called Projects that displays projects I have worked on. While on the projects page I would like to click on the actual projects and go to their respective sites as demonstrated in the codeblock below. The below code works, but it seems wrong. I tried nesting it so it looks like image2:
When I add <Outlet/> to my ProjectsPage component, it sure renders the child routes. However, it also renders the parent page. Ideally I want them to be rendered independtly. I hope this makes sense.
Code Block 1 – Nested routes:
<Router>
<Header />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/projects" element={<ProjectsPage />}>
<Route path="portfolio" element={<PortfolioProject />} />
<Route path="realestateapp" element={<RealEstateProject />} />
</Route>
<Route path="*" element={<NoPage />} />
</Routes>
<Footer />
</Router>
Code Block 2 – Non nested routes:
<Router>
<Header />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/projects" element={<ProjectsPage />} />
<Route path="/projects/portfolio" element={<PortfolioProject />} />
<Route path="/projects/realestateapp" element={<RealEstateProject />} />
<Route path="*" element={<NoPage />} />
</Routes>
<Footer />
</Router>
>Solution :
Your "code1" example isn’t the same as "code 2" since it renders ProjectsPage as a layout route. If you want the two code examples to be equivalent then you should render ProjectsPage as an index route under the "/projects" layout route.
Example:
<Router>
<Header />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/projects">
<Route index element={<ProjectsPage />}>
<Route path="portfolio" element={<PortfolioProject />} />
<Route path="realestateapp" element={<RealEstateProject />} />
</Route>
<Route path="*" element={<NoPage />} />
</Routes>
<Footer />
</Router>
<Router>
<Header />
<Routes>
<Route path="/" element={<Home />} />
<Route path="/projects" element={<ProjectsPage />} />
<Route path="/projects/portfolio" element={<PortfolioProject />} />
<Route path="/projects/realestateapp" element={<RealEstateProject />} />
<Route path="*" element={<NoPage />} />
</Routes>
<Footer />
</Router>