Search code examples
javascriptreactjsreact-starter-kit

Roles of routes and components in React Starter Kit


I am currently trying to understand the way React Starter Kit lays out the project and how its part work together.

Currently struggling with routes and components. The role of routes is to decide what to display on a certain path but then there are components with App and all its sub-components, which are displayed.... around what routes define?

It seems like what's in App is always displayed. And routes define what to display inside of App as part of its children, is that correct?


Solution

  • No. What is inside your App component does not always gets displayed unless or until you have defined App as root component inside your routes configuration.

    e.g

      <Router history={browserHistory}>
        <Route path="/" component={App}>
          <Route path="about" component={About}/>
          <Route path="users" component={Users}>
            <Route path="/user/:userId" component={User}/>
          </Route>
          <Route path="*" component={NoMatch}/>
        </Route>
      </Router>
    

    In above code defining

      <Route path="/" component={App}>
    

    causes App component to be displayed first and all other route path are children of App component.

    So for the second part of your question - "routes define what to display inside of App as part of its children, is that correct"

    Yes you are right - But to display other components as children of root component, you have to mention it in render method of your root component via

        {this.props.children}
    

    e.g

    const App = React.createClass({
      render() {
        return (
          <div>
            <h1>App</h1>
            <ul>
              <li><Link to="/about">About</Link></li>
              <li><Link to="/users">users</Link></li>
            </ul>
            {this.props.children}
          </div>
        )
      }
    })
    

    So Now you are telling that when url is / display my root component i.e App and if route is /about or /users display children components of App i.e About or Users component.

    Your root component App is like a template where you show header, navigation bar, footer as static content. But body part where you say

    {this.props.children} 
    

    is changing as your route changes with your children components.