5

I've upgraded the react router to version 4 in my application. But now I'm getting the error

Warning: You should not use <Route component> and <Route children> in the same route; <Route children> will be ignored

What is wrong with this routing?

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

render((
    <Router history={ browserHistory }>
        <Switch>
            <Route path='/' component={ Main }>
                <IndexRoute component={ Search } />
                <Route path='cars/:id' component={ Cars } />
                <Route path='vegetables/:id' component={ Vegetables } />
            </Route>
            <Redirect from='*' to='/' />
        </Switch>
    </Router>
), document.getElementById('main'))
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
user3142695
  • 15,844
  • 47
  • 176
  • 332

2 Answers2

10

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='/' component={ Main }/>

            <Redirect from='*' to='/' />
        </Switch>
    </Router>
), document.getElementById('main'))

Then in the Main Component

render() {
     const {match} = this.props;
     return (
        <div>
           {/* other things*/}
           <Route exact path="/" 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>
    )

}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • Naked JS template literals are no longer allowed in JSX. Therefore you need to use something along these lines: – ivosh Feb 19 '18 at 12:54
  • 1
    Be careful where you use exact when using nested routes. Exact will match only that exact path for example exact="/" doesn't match /posts/:id - this tripped me up a bit as a new user when trying to do a nested layout. – dubvfan87 Sep 20 '18 at 15:26
0

Nested routes are not available from version react-router 4.x. Here is a basic example straight from react-router documentation on how to code for nesting route secnarios in v4.x.

Also have a look on this question as well Why can I not nest Route components in react-router 4.x?

Upasana
  • 1,937
  • 1
  • 14
  • 17