Reputation: 55
I cant seem to render multiple Route elements in a single Routes element. I would like to have a multiple Route elements in a single Routes element since they are both updated dynamically. Does the old syntax/style not work?
Code example:
import React from 'react';
import './App.css';
import Header from './Header';
import Home from './Home';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';
function App() {
return (
// use BEM naming convention
<Router>
<div className="app">
<Routes>
{/* This one works */}
{/* <Route path="/" element={<><Header /><Home /></>} /> */}
{/* But this doesnt: */}
<Route path="/" element={<Header />} />
<Route path="/" element={<Home />} />
</Routes>
</div>
</Router>
);
}
export default App;
Upvotes: 3
Views: 1964
Reputation: 202686
There should be only one Route
per path you want to match. In react-router-dom@6
all routes are exclusively matched, the Routes
component serves a similar purpose to, and is the spiritual successor of, the RRDv5 Switch
component.
If you are trying to render common UI logic/components then the recommended way is to use what are called Layout Routes that renders the common logic/UI and an Outlet
component for nested Route
components to render their element
into.
If you want to render a Header
component on specific routes then create a layout component that renders the Header
and Outlet
and wrap the routes you want to render with Header
.
Example:
import { Outlet } from 'react-router-dom';
import Header from '../path/to/Header';
const HeaderLayout = () => (
<>
<Header />
<Outlet /> // <-- nested routes render content here
</>
);
export default HeaderLayout;
...
import React from 'react';
import './App.css';
import HeaderLayout from './HeaderLayout';
import Home from './Home';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';
function App() {
return (
// use BEM naming convention
<Router>
<div className="app">
<Routes>
<Route element={<HeaderLayout />}>
<Route path="/" element={<Home />} /> // <-- nested route
... other routes with Header
</Route>
... other routes w/o Header
</Routes>
</div>
</Router>
);
}
Upvotes: 1