Nesting Routes in react-router v4

IndexRoute and browserHistory are not available in the latest version, also Routes do not accept children Routes with v4, Instead, you can specify Routes within the component Itself

import {
    Switch,
    BrowserRouter as Router,
    Route,  Redirect
} from 'react-router-dom'   

render((
    <Router>
        <Switch>
            <Route exact path="https://stackoverflow.com/" component={ Main }/>

            <Redirect from='*' to="https://stackoverflow.com/" />
        </Switch>
    </Router>
), document.getElementById('main'))

Then in the Main Component

render() {
     const {match} = this.props;
     return (
        <div>
           {/* other things*/}
           <Route exact path="https://stackoverflow.com/" component={ Search } />
           <Route path={`${match.path}cars/:id`} component={ Cars } />
         </div>
    )

}

Similarly in the cars component

you will have

render() {
     const {match} = this.props;
     return (
        <div>
           {/* other things*/}
           <Route path={`${match.path}/vegetables/:id`} component={ Vegetables } />
        </div>
    )

}

Leave a Comment