React Router - Tuong-Nguyen/JavaScript-Structure GitHub Wiki
- Navigation
- Keep UI in sync with the URL
npm install --save react-router
- It's component that does not create DOM itself, but to coordinate other components that do.
-
historyproperty has 2 options:hashHistoryandbrowserHistory
<Router history={hashHistory}>
...
</Router>- 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 inwindow.sessionStoragebetween page loads
For dynamic page, using it, we must have a server. Read more
- Takes 2 properties
pathandcomponent - When a path matches the
pathgiven to the<Route>component, it will return thecomponentspecified.
<Route path="/" component={App}/>-
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>- Get
path
this.props.location.pathname- Get parameter
this.props.params.filter- To define the default component will be rendered if a route has children.
-
IndexRoutehas 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>- 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>- is similar to using an html anchor tag.
-
toproperty: set URL value
import {Link} from 'react-router';<Link to="/" activeClassName="selected"/>-
activeClassName: if the link is active, it's set to a class
- 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');