Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  54] [ 7]  / answers: 1 / hits: 43494  / 7 Years ago, mon, april 3, 2017, 12:00:00

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>
);

More From » reactjs

 Answers
1

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.


[#58294] Friday, March 31, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
haden

Total Points: 638
Total Questions: 95
Total Answers: 99

Location: Burundi
Member since Wed, Nov 25, 2020
4 Years ago
;