g3blv
g3blv

Reputation: 4367

Nested components with React Router

I'm following an online React tutorial. In the tutorial React Router 3 used while I got React Router 4 when I downloaded React Router (and react-router-dom). The code in the tutorial looks like this.

import React from "react";
import {render} from "react-dom";
import {Router, Route, browserHistory} from 'react-router'

import {Root} from "./components/Root";
import {Home} from "./components/Home";
import {User} from "./components/User";

class App extends React.Component {
    render() {
        return (
            <Router history={browserHistory}>
                <Route path={"/"} component={Root}>
                    <Route path={"user"} component={User}/>
                    <Route path={"home"} component={Home}/>
                </Route>
            </Router>
        );
    }
}

render(<App />, window.document.getElementById('app'));  

I'm trying to rewrite the code to work with React Router 4 like this:

import React from "react";
import {render} from "react-dom";
import {Switch, BrowserRouter, Route} from 'react-router-dom'

import {Root} from "./components/Root";
import {Home} from "./components/Home";
import {User} from "./components/User";

class App extends React.Component {
    render() {
        return (
            <BrowserRouter>
                <Switch>
                    <Route path="/" component={Root}>
                        <Route path="/user" component={User}/>
                        <Route path="/home" component={Home}/>
                    </Route>
                </Switch>
            </BrowserRouter>
        );
    }
}

render(<App />, window.document.getElementById('app'));

This gives me an error:

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

I've tried wrapping the child components with <Switch> and <Root> but it didn't work. How should the child components be wrapped?

Upvotes: 0

Views: 1266

Answers (1)

Shota
Shota

Reputation: 7330

In React Router 4 you don't nest routes anymore. In your case what you can do is to put your routes in your child component, like this:

class App extends React.Component {
    render() {
        return (
            <BrowserRouter>
                <Route path="/" component={Root} />
            </BrowserRouter>
        );
    }
}

class Root extends React.Component {
    render() {
        return (
            <div>
                <Route path="/user" component={User}/>
                <Route path="/home" component={Home}/>
            </div>
        );
    }
}

Also, I don't think you need to use Switch here, as it will only match one first child route and it does not seem to be needed in your case.

Upvotes: 3

Related Questions