Router in React - Tuong-Nguyen/JavaScript-Structure GitHub Wiki

React Router is a routing library for React. It enables us to map a URL to components.

Installation

npm install --save react-router

Usage

Import essential components and use them.

import { Router, Route, hashHistory } from 'react-router';

render(
  <Router history={hashHistory}>
    <Route path="/" component={App}/>
    <Route path="list-days" component={App} />
    <Route path="add-day" component={App} />
    <Route path="*" component={Whoops404}/>
  </Router>,
  document.getElementById('react-container')
)

Router component would route URL to Route component that has the path attribute matching with the path of URL. And the component in that Route component would be instantiated and rendered.

Using route parameters

React Router could understand parameters in URL by using the following declarations:

  • Declaring within the path attribute of Route component
<Route path="list-days(/:filter)(/:test)" component={App} />
  • Declaring child Routes within Route component
<Route path="list-days" component={App} >
     <Route path=":filter" component={App} >
         <Route path=":order" component={App} />
     </Route>
</Route>

Considering the URL: https://localhost/list-days/red/yellow/

As declarations and URL above, we would have two parameters as following:

  • filter = "red"
  • order = "yellow"

And parameters are optional

Getting parameters and path

In the components, we could get parameters and path in the URL by props

pathname = this.props.location.pathname;
filter = this.props.params.filter;
order = this.props.params.filter;

Nesting routes

Creating nested routes is making one route a child of another as following

const routes = (
    <Router history={hashHistory}>
        <Route path="/" component={Home} />
        <Route path="/" component={Left}>
        	<Route path="about" component={About} />
        	<Route path="members" component={MemberList} />
        </Route>
        <Route path="*" component={Whoops404} />
    </Router>
)

render(routes, document.getElementById('react-container'))

A route's component is rendered when that route matches the URL. For example, if the URL is http://localhost/about then Left and About component would be rendered. About component is a child of Left component, it would be got in props of Left component.

export const Left = (props) => 
	<div className="page">
		<MainMenu className="main-menu"/>
		{props.children}
	</div>

{props.children} is result of render method of About component.

So, a child route would be a property of parent route and got by children property. Also, in the props contains some properties such as location, params...

⚠️ **GitHub.com Fallback** ⚠️