Learn how to add routing to your React App
npm install -g create-react-app
# create with create-react-app PROJECT_NAME
create-react-app router-example
# change into the router-example directory
cd router-example
npm i react-router --save # install dev
We need to refactor how the application serves components
Create a Root.js file in /src
import React, { Component } from 'react'
import { Link } from 'react-router'
import { Home } from '../../Containers'
export default class Root extends Component {
render() {
return (
<div>
{this.props.children}
</div>
)
}
}
this.props.children is dynamic and will serve the correct component that matches our route config step
/* /src/index.js */
<Router history={browserHistory}>
<Route path="/" component={Root}>
</Route>
</Router>
/* /src/index.js */
<Router history={browserHistory}>
<Route path="/" component={Root}>
<IndexRoute component={Home} />
</Route>
</Router>
/* /src/index.js */
<Router history={browserHistory}>
<Route path="/" component={Root}>
<IndexRoute component={Home} />
<Route path="/post/:id" component={ParamsExample} />
</Route>
</Router>
/* /src/index.js */
<Router history={browserHistory}>
<Route path="/" component={Root}>
<IndexRoute component={Home} />
<Route path="/post/:id" component={ParamsExample} />
<Route path="/query" component={QueryExample} />
</Route>
</Router>
/* /src/index.js */
<Router history={browserHistory}>
<Route path="/" component={Root}>
<IndexRoute component={Home} />
<Route path="/post/:id" component={ParamsExample} />
<Route path="/query" component={QueryExample} />
<Route path="programmatic" component={ProgrammaticExample} />
</Route>
</Router>
/* /src/index.js */
<Router history={browserHistory}>
<Route path="/" component={Root}>
<IndexRoute component={Home} />
<Route path="/post/:id" component={ParamsExample} />
<Route path="/query" component={QueryExample} />
<Route path="*" component={FourOFour}/>
</Route>
</Router>
<Link>
Componentuse history.go