I'm updating my universal react redux app to use react router v4. I have nested routes under a main layout route. Previously I used {props.children} to show contents of child routes, but this doesn't work anymore. How does this work in V4?
<Provider store={store} key="provider"> <div> <Route component={Layout} /> <Switch> <Route path="/" component={HomePage} /> <Route component={Error404} /> </Switch> </div> </Provider>
or
<Provider store={store} key="provider"> <Layout> <Route path="/" component={HomePage} /> <Route component={Error404} /> </Layout> </Provider>
This is how my Layout file looks
const Layout = props => ( <div className="o-container"> <Header /> <main> {props.children} </main> <Footer /> </div> );
Now, the last thing you need to do is tell React Router where in the parent Route ( Messages ) should it render the child Route ( Chats ). To do this, you use React Router's Outlet component. If the app's location matches the nested Route 's path , this Outlet component will render the Route 's element .
First issue is that the root route is only rendered when it exactly matches "/login" , so if the URL/path becomes "/login/dados" it no longer matches exactly and Login is unmounted. Remove the exact prop on the root Route component so subroutes/nested routes can be matched and rendered. Show activity on this post.
Routes can be nested inside one another, and their paths will nest too (child inheriting the parent).
I have taken the <Provider>
out because it belongs to react-redux
and you don't need it as basis for routing with react-router
(anyway you can easily add it encapsulating the structure with it).
In React Router V4, what was Router
has been renamed to BrowserRouter
and imported from package react-router-dom
. So for nesting routes you need to insert this as children of your <Layout>
.
index.js
import { Switch, Route } from 'react-router'; import { BrowserRouter } from 'react-router-dom'; import Layout from './Layout'; ... const Root = () => ( <Layout> <BrowserRouter> <Switch> <Route exact path="/" component={HomePage} /> <Route path="/other" component={OtherComponent} /> <Route component={Error404} /> </Switch> </BrowserRouter> </Layout> ); ReactDOM.render( <Root/>, document.getElementById('root') );
Layout.js
import React from 'react'; import Header from './Header'; import Footer from './Footer'; const Layout = props => ({ render() { return ( <div className="o-container"> <Header /> <main>{props.children}</main> <Footer /> </div> ); } }); export default Layout;
Take in count this only works for web. Native implementation differs.
I uploaded a small project based in Create React App where I show the implementation of nested routes in V4.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With