I'm an absolute biginner with React and I'm experiencing a really (hopefully) simple problem with routes in React (v6). I have:
- 1 NavBar
- 2 components
I would like to access the two components through the "NavBar menu" using React routes 6 but I'm not able to fix the NavBar at the top. It disappears as soon as I navigate to the component.
I will explain it using an image:

This is my configuration:
function App() {
return (
<Router>
<div className="App">
<Routes>
<Route path="/" element={<NavBar />} />
<Route exact path="/componenta" element={<ComponentA />} />
<Route exact path="/componentb" element={<ComponentB />} />
</Routes>
</div>
</Router>
);
}
And if you want here you can find the related CodeSandbox: https://codesandbox.io/s/pensive-river-5n6go?file=/src/App.js
How can I properly configure the routes (v6) to get it work correctly? Thanks for your help.
CodePudding user response:
If you want to render a navbar regardless of route then render it outside the Routes component.
function App() {
return (
<Router>
<div className="App">
<NavBar />
<Routes>
<Route path="/componenta" element={<ComponentA />} />
<Route path="/componentb" element={<ComponentB />} />
</Routes>
</div>
</Router>
);
}
If you want to conditionally render the navbar only with specific routes then render it as a layout component that also renders an Outlet for nested Route components.
function App() {
return (
<Router>
<div className="App">
<Routes>
<Route
element={(
<>
<NavBar />
<Outlet />
</>
)}
>
<Route path="/componenta" element={<ComponentA />} />
<Route path="/componentb" element={<ComponentB />} />
</Route>
... other routes without navbar
</Routes>
</div>
</Router>
);
}
CodePudding user response:
Pull NavBar outside of Routes:
<NavBar />
<Routes>
<Route exact path="/componenta" element={<ComponentA />} />
<Route exact path="/componentb" element={<ComponentB />} />
</Routes>
Then it should render at the top of the app div, and route changes will render the selected component beneath it.
