0

Working on getting React-Router working for an SPA but I can't seem to get it to render anything other than the App component.

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, IndexRoute, browserHistory } from 'react-router';
import Parameter from './components/parameter/Parameter';

class App extends React.Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div className="container">
                <h1>TEST</h1>
                <Link to="/parameter">Click Me!</Link>
            </div>
        )
    }
}

class Test extends React.Component {
    render() {
        return (
            <div className="container">
                <h1>TEST PAGE</h1>
            </div>
        )
    }
}

var routes = (
    <Route name="root" component={App} path="/">
        <Route component={Test} path="test" />
        <Route component={Parameter} path="parameter" />
    </Route>
)

ReactDOM.render((
    <Router history={browserHistory} routes={routes} />
), document.getElementById('react'))
greyfox
  • 6,426
  • 23
  • 68
  • 114

2 Answers2

2

You aren't specifying where you want the nested components to render within the App component. The App component behaves something like a layout for all nested routes.

The components you specify for nested routes need a place to go within a layout / parent component when a particular route is hit.

The simplest way to get this working is to use {this.props.children} somewhere in your App component. Refer to my example below.

Here is your App component again:

class App extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div className="container">
                <h1>TEST</h1>
                <Link to="/parameter">Click Me!</Link>
                {this.props.children}
            </div>
        )
    }
}

For a more in-depth example, refer to the active-links example from the react-router repo. In their example, you can see that children is available as props within the App component and will render any of the other components from nested routes when a relevant route is hit. For example, hitting the / route will render the Index component within App where {children} is positioned because there is a directly nested route <IndexRoute ... /> that exists.

React provides this.props.children as a way to access a component's children. It allows you to pass components as data to another component. In this case, rendering the child component within the App component.

cheersjosh
  • 1,139
  • 8
  • 15
0

If you are using React Router v4, I think the reason the nested components are not rendering is because you can't nest <Route />s in React Router v4.

I opened up a question on this earlier:

How to nest routes in React Router v4?

Community
  • 1
  • 1
Raphael Rafatpanah
  • 19,082
  • 25
  • 92
  • 158