1

I am trying to find documentation from the react router website https://reacttraining.com/react-router, and I cant seem to find a solution to have nested routes work in 4.1.1. For example in the older version of React Router, you would be able to nest Routes like so:

<Router history={history}>
    <Route exact path="/" component={App}>
        <Route path="/cards" component={Example} />
    </Route>
</Router>

This used the {this.props.children} and made it easy to have static components such as a navbar exist all through the application without having to import it in every component.

class App extends Component {
    render() {
        return (
            <div>
                <Header/>
                    <main>{ this.props.children }</main>
                <Footer/>
            </div>
        );
    }
}

How can I have similar behavior with version 4.1.1. I do not want to import the header component all the time in the components.

I am using at the moment, but it does not seem to accomplish what I am trying to do.

    <Router history={history}>
        <Switch>
            <Route exact path="/" component={App}>
                <Route path="/cards" component={Example} />
            </Route>
        </Switch>
    </Router>
henhen
  • 1,038
  • 3
  • 18
  • 36
  • Possible duplicate of [Use nested Routes in react-router v4](https://stackoverflow.com/questions/44452858/use-nested-routes-in-react-router-v4) – Shubham Khatri Jun 22 '17 at 19:46

1 Answers1

4

In v4 it's much easier actually since <Route /> is just normal component like any other. Instead of needing to use props.children you can put your routes exactly where you need the matching component to render. The following is equivalent to your v3 example:

<Router>
  <div>
    <Header />
    <main>
      <Route exact path="/" component={HomePage} />
      <Route path="/cards" component={Example} />
    </main>
    <Footer />
  </div>
</Router>

Updated answer to include an "index" path.

azium
  • 20,056
  • 7
  • 57
  • 79
  • 1
    v3 and v4 differ in this respect. v4 doesn't really have the concept of a routes file. free your mind from a routes file and just remember that wherever your route is placed, is where the component will load as long the path matches. – azium Jun 22 '17 at 18:53