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

  • Navigation
  • Keep UI in sync with the URL

Install

npm install --save react-router

Router

  • It's component that does not create DOM itself, but to coordinate other components that do.
  • history property has 2 options: hashHistory and browserHistory
<Router history={hashHistory}>
  ...
</Router>

hashHistory

  • For static page
  • When using hash history, you’ll see an extra item in your query string that looks something like _k=123abc. This is a key that history uses to look up persistent state data in window.sessionStorage between page loads

browserHistory

For dynamic page, using it, we must have a server. Read more

Route

  • Takes 2 properties path and component
  • When a path matches the path given to the <Route> component, it will return the component specified.
<Route path="/" component={App}/>

path

  • path: an Express-style string, an array of strings, or a regular expression.
  • Be understood by path-to-regexp package
<Route path="/" component={App}>
  <!-- Route has path as parameter -->
  <Route path=":filter" component={App}/>
</Route>

Getter

  • Get path
  this.props.location.pathname
  • Get parameter
  this.props.params.filter

IndexRoute

  • To define the default component will be rendered if a route has children.
  • IndexRoute has same path to the parent
<Router>
  <Route path="/" component={App}>
    <IndexRoute component={Home}/>
    <Route path="accounts" component={Accounts}/>
    <Route path="statements" component={Statements}/>
  </Route>
</Router>

IndexRedirect

  • Redirect to a route if the parent route is accessed
<Route path="/" component={App}>
  <IndexRedirect to="/welcome" />
  <Route path="welcome" component={Welcome} />
  <Route path="about" component={About} />
</Route>

Link

  • is similar to using an html anchor tag.
  • to property: set URL value

Import

import {Link} from 'react-router';

Usage

<Link to="/" activeClassName="selected"/>
  • activeClassName: if the link is active, it's set to a class

Redirect using Router

  • Access router from context: declare contextTypes
class ManageCoursePage extends Component{
    
}

ManageCoursePage.contextTypes = {
    router: PropTypes.object.isRequired
}
  • Change URL using push
   this.context.router.push('/courses');
⚠️ **GitHub.com Fallback** ⚠️