Im using react: 17.0.2
and react-router-dom: 6.3.0
.
My current App.js
snippet looks like this:
class App extends React.Component {
render() {
return (
<div className="App">
<Routes>
<Route element={<Layout/>}>
<Route path="/home" element={<Home/>} />
<Route path="/login" element={<Login/>} />
<Route path="/signup" element={<Signup/>} />
</Route>
<Route exact path='/' element={<Intro/>}/>
</Routes>
</div>
);
}
}
The route to '/'
should not use the Layout
component, so I need to exclude it from the context.
Within Layout.js
I need to access the children
like so:
const Layout = ({ children }) => {
console.log(children)
return (
<div>
<main>{children}</main>
</div>
);
};
But children
are undefined
in the above example. I can access children
in Layout.js
when I rewrite App.js
to the below snippet, but then '/'
is also rendered with the Layout.
class App extends React.Component {
render() {
return (
<div className="App">
<Layout>
<Routes>
<Route path="/home" element={<Home/>} />
<Route path="/login" element={<Login/>} />
<Route path="/signup" element={<Signup/>} />
<Route exact path='/' element={<Intro/>}/>
</Routes>
</Layout>
</div>
);
}
}
export default App;
How can I access children
in Layout.js
and render path '/'
without the layout.
CodePudding user response:
Route
and Routes
work a little differently in v6. The Route
and React.Fragment
components are the only valid children of the Routes
component, and other Route
components the only valid children of the Route
. Layout routes must render an Outlet
component for the nested routes to render their contents into.
import { Outlet } from 'react-router-dom';
const Layout = () => {
return (
<div>
<main>
<Outlet />
</main>
</div>
);
};