SlideShare une entreprise Scribd logo
1  sur  76
Télécharger pour lire hors ligne
React Router
React Meetup XXL - September 23, 2015
-Rob Gietema @robgietema
Who am I?
What is react-router?
Routing url to React Component
Route /aboutto <About />
Route /user/1234to <User />
Route /user/1234?message=Hito <User />
Michael Jackson & Ryan Florence
2.002 commits
53 releases
197 contributors
180k downloads / month
What does it look like?
Defining routes
Simple example
import { Route } from 'react-router';
const routes = (
<Route handler={App} path="/">
<Route name="about" handler={About} />
</Route>
);
About page is available at /about
Using custom path
import { Route } from 'react-router';
const routes = (
<Route handler={App} path="/">
<Route name="about" path="my-about" handler={About} />
</Route>
);
About page is available at /my-about
Default route
import { Route, DefaultRoute } from 'react-router';
const routes = (
<Route handler={App} path="/">
<DefaultRoute handler={Home} />
<Route name="about" handler={About} />
</Route>
);
Home is available at /
Not found route
import { Route, NotFoundRoute } from 'react-router';
const routes = (
<Route handler={App} path="/">
<Route name="about" handler={About} />
<NotFoundRoute handler={NotFound}/>
</Route>
);
Nesting
import { Route } from 'react-router';
const routes = (
<Route handler={App} path="/">
<Route name="users" handler={Users}>
<Route name="recent-users" path="recent"
handler={RecentUsers} />
</Route>
</Route>
);
Recent users available at /users/recent
Params
import { Route } from 'react-router';
const routes = (
<Route handler={App} path="/">
<Route name="users" handler={Users}>
<Route name="user" path="/user/:userId" handler={User} />
</Route>
</Route>
);
User 1234is available at /user/1234
Multiple params
import { Route } from 'react-router';
const routes = (
<Route handler={App} path="/">
<Route name="users" handler={Users}>
<Route name="user-message"
path="/user/:userId/message/:messageId"
handler={User} />
</Route>
</Route>
);
Example /users/123/message/456
Redirect routes
import { Route, Redirect } from 'react-router';
const routes = (
<Route handler={App} path="/">
<Route name="about" handler={About} />
<Redirect from="company" to="about" />
</Route>
);
/companywill be redirected to /about
Redirect routes with params
import { Route, Redirect } from 'react-router';
const routes = (
<Route handler={App} path="/">
<Redirect from="/user/me" to="user" params={{userId: MY_ID}} />
<Route name="user" path="/user/:userId" handler={User} />
</Route>
);
Notice the order of the routes
Without nesting
import { Route, Redirect } from 'react-router';
const routes = [
<Route name="about" handler={About} />,
<Route name="contact" handler={Contact} />
];
Array of routes
Include external routes
import { Route, Redirect } from 'react-router';
import aboutRoutes from 'about/routes';
const routes = {
<Route handler={App} path="/">
<Redirect from="/user/me" to="user" params={{userId: MY_ID}} />
<Route name="user" path="/user/:userId" handler={User} />
{aboutRoutes}
</Route>
};
Running the router
Using hashes
import React from 'react';
import Router from 'react-router';
Router.run(routes, (Handler) => {
React.render(<Handler/>, document.body);
});
Location will be http://localhost/#/aboutetc.
Using HTML5 History
import React from 'react';
import Router from 'react-router';
Router.run(routes, Router.HistoryLocation, (Handler) => {
React.render(<Handler/>, document.body);
});
Location will be http://localhost/aboutetc.
Using Universal Rendering
import React from 'react';
import Router from 'react-router';
app.serve((req, res) => {
Router.run(routes, req.path, function (Handler) {
const html = React.renderToString(Handler);
res.send(html);
});
});
Render html to the client
Rendering the routes
App component
import React from 'react';
import { RouterHandler } from 'react-router';
class App extends React.Component {
render() {
return (
<div>
<h1>Hello World!</h1>
<RouterHandler />
</div>
);
}
}
Use RouterHandlerto render matched route
Access router methods
ES5
import React from 'react';
var User = React.createClass({
contextTypes: {
router: React.PropTypes.func
},
render: function () {
return <h1>Hello World</h1>;
}
}
Available in render self.context.router
ES6
import React from 'react';
class User extends React.Component {
render() {
return <h1>Hello World</h1>;
}
}
User.contextTypes = {
router: React.PropTypes.func
};
Available in render self.context.router
ES7
import React from 'react';
class User extends React.Component {
static contextTypes = {
router: React.PropTypes.func,
}
render() {
return <h1>Hello World</h1>;
}
}
Available in render self.context.router
Available router methods
Getting params
import React from 'react';
class User extends React.Component {
static contextTypes = {
router: React.PropTypes.func,
}
render() {
const user = this.context.router.getCurrentParams().userId;
return <h1>Hello user {user}</h1>;
}
}
From route /user/:userId
Getting query params
import React from 'react';
class User extends React.Component {
static contextTypes = {
router: React.PropTypes.func,
}
render() {
const message = this.context.router.getCurrentQuery().message;
return <h1>{message}</h1>;
}
}
From url /user/1234?message=Hello%20World
Getting current routes
import React from 'react';
class User extends React.Component {
static contextTypes = {
router: React.PropTypes.func,
}
render() {
const routes = this.context.router.getCurrentRoutes();
...
}
}
Array of routes in nesting order
Fetching data
import React from 'react';
import Router from 'react-router';
Router.run(routes, (Handler, state) => {
fetchData(state).then(() => {
React.render(<Handler/>, document.body);
});
});
Fetching data
function fetchData(state) {
return Promise.all(state.routes.filter((route) => {
return route.handler.fetchData;
}).map((route) => {
return route.handler.fetchData(state.params, state.query);
});
}
Fetching data
import React from 'react';
class User extends React.Component {
static fetchData(params) {
return new Promise((resolve) => {
MyApi.loadSomething(() => {
resolve();
});
});
}
...
}
isActive method
import React from 'react';
class Tab extends React.Component {
static contextTypes = {
router: React.PropTypes.func,
}
render() {
const isActive = this.isActive(this.props.to);
const className = isActive ? 'active' : '';
return <li className={className}><Link {...this.props} />;
}
}
Call with <Tab to="about">About</Tab>
Navigating between routes
Using href
import React from 'react';
class User extends React.Component {
render() {
return (
<a href="/about">About</a>
);
}
}
Don't use this!
Using Link Component
import React from 'react';
import { Link } from 'react-router';
class User extends React.Component {
render() {
return (
<Link to="about">About</Link>
);
}
}
Will generate <a href="/about">About</a>
Using Link Component
import React from 'react';
import { Link } from 'react-router';
class About extends React.Component {
render() {
return (
<Link to="user" params={{userId: 1234}}>User 1234</Link>
);
}
}
With params
Using Link Component
import React from 'react';
import { Link } from 'react-router';
class About extends React.Component {
render() {
return (
<Link to="contact" query={{message: 'Hi'}}>Say hi</Link>
);
}
}
Will generate /contact?message=Hi
Using makeHref
import React from 'react';
class User extends React.Component {
static contextTypes = {
router: React.PropTypes.func,
}
render() {
const link = this.context.router.makeHref('about');
return (
<a href={link}>About</a>
);
}
}
Using makeHref
import React from 'react';
class About extends React.Component {
static contextTypes = {
router: React.PropTypes.func,
}
render() {
const link = this.context.router.makeHref('user',
{ userId: 1234 },
{ message: 'Hi'});
return (
<a href={link}>About</a>
);
}
}
With params and query params
Using transitionTo
import React from 'react';
class User extends React.Component {
static contextTypes = {
router: React.PropTypes.func,
}
onSubmit() {
this.context.router.transitionTo('about');
}
...
}
Will transition to /about
Using transitionTo
import React from 'react';
class About extends React.Component {
static contextTypes = {
router: React.PropTypes.func,
}
onSubmit() {
this.context.router.transitionTo('user',
{userId: 1234});
}
...
}
Will transition to /user/1234
Using transitionTo
import React from 'react';
class About extends React.Component {
static contextTypes = {
router: React.PropTypes.func,
}
onSubmit() {
this.context.router.transitionTo('contact',
{},
{message: 'Hi'});
}
...
}
Will transition to /contact?message=Hi
Using replaceWith
import React from 'react';
class User extends React.Component {
static contextTypes = {
router: React.PropTypes.func,
}
onSubmit() {
this.context.router.replaceWith('about');
}
...
}
Not added to browser history
Using goBack
import React from 'react';
class About extends React.Component {
static contextTypes = {
router: React.PropTypes.func,
}
onClick() {
this.context.router.goBack();
}
...
}
Go back one step in history
goForward
import React from 'react';
class About extends React.Component {
static contextTypes = {
router: React.PropTypes.func,
}
onClick() {
this.context.router.goForward();
}
...
}
Go forward one step in history
go(n)
import React from 'react';
class About extends React.Component {
static contextTypes = {
router: React.PropTypes.func,
}
onClick() {
this.context.router.go(2);
}
...
}
Go forward two steps in history
go(-n)
import React from 'react';
class About extends React.Component {
static contextTypes = {
router: React.PropTypes.func,
}
onClick() {
this.context.router.go(-2);
}
...
}
Go backward two steps in history
Lifecycle methods
willTransitionTo
import React from 'react';
class User extends React.Component {
static willTransitionTo(transition) {
if (!auth.loggedIn()) {
transition.redirect('/login',
{},
{'redirect' : transition.path});
}
}
...
}
willTransitionFrom
import React from 'react';
class User extends React.Component {
static willTransitionFrom(transition) {
if (!form.validate()) {
transition.abort();
}
}
...
}
Changes in 1.0
Handler to component
import { Route } from 'react-router';
const routes = (
<Route handler={App} path="/">
<Route name="about" handler={About} />
</Route>
);
...
const routes = (
<Route component={App} path="/">
<Route path="about" component={About} />
</Route>
);
RouterHandler to props
class App extends React.Component {
render() {
return (
<RouterHandler />
);
}
}
class App extends React.Component {
render() {
return (
{this.props.children}
);
}
}
No more named routes
<Route handler={App} path="/">
<Route name="user" path="/user/:userId" handler={User} />
</Route>
...
<Route component={App} path="/">
<Route path="/user/:userId" component={User} />
</Route>
Not found route
<NotFoundRoute handler={NotFound} />
...
<Route path="*" component={NotFound} />
Catch all
Redirect routes
<Route handler={App} path="/">
<Redirect from="/user/me" to="user" params={userId: '1234'} />
<Route name="user" path="/user/:userId" handler={User} />
</Route>
...
<Route component={App} path="/">
<Redirect from="/user/me" to="/user/1234" />
<Route path="/user/:userId" component={User} />
</Route>
Params in the url
Default route
<Route handler={App} path="/">
<DefaultRoute handler={Home} />
<Route name="about" handler={About} />
</Route>
...
<Route component={App} path="/">
<IndexRoute component={Home} />
<Route path="about" component={About} />
</Route>
Home is available at /
Multiple components
import { Route } from 'react-router';
const routes = (
<Route component={App}>
<Route path="users" components={{main: Users,
sidebar: UsersSidebar}}/>
</Route>
);
Multiple components
import React from 'react';
class App extends React.Component {
render() {
return (
<div>
<div className="Main">
{this.props.main}
</div>
<div className="Sidebar">
{this.props.sidebar}
</div>
</div>
);
}
}
Running the router
Router.run(routes, (Handler) => {
React.render(<Handler/>, document.body);
});
...
import { history } from 'react-router/lib/HashHistory';
React.render((
<Router history={history}>
{routes}
</Router>
), document.body);
History options
import { history } from 'react-router/lib/HashHistory';
import { history } from 'react-router/lib/BrowserHistory';
import { history } from 'react-router/lib/MemoryHistory';
Using makeHref
const link = this.context.router.makeHref('user',
{ userId: 1234 },
{ message: 'Hi'});
...
const link = this.context.router.createHref('/user/1234',
{ message: 'Hi'});
Params in the link
Link component
<Link to="user" params={{userId: MY_ID}}>John Do</Link>
...
<Link to={'/users/' + MY_ID}>John Do</Link>
Params in the link
transitionTo
this.context.router.transitionTo(pathname, params, query)
this.context.router.transitionTo('user',
{ userId: 1234 },
{ message: 'Hi' });
...
this.context.router.transitionTo(pathname, query, state)
this.context.router.transitionTo('/user/1234',
{ message: 'Hi' });
willTransitionTo to onEnter
class User extends React.Component {
static willTransitionTo(transition) {
...
}
}
___
function requireAuth(nextState, transition) {
...
}
const routes = (
<Route component={App} path="/">
<Route path="about" component={About} onEnter={requireAuth} />
</Route>
);
willTransitionFrom to onLeave
class User extends React.Component {
static willTransitionFrom(transition) {
...
}
}
___
function handler(nextState, transition) {
...
}
const routes = (
<Route component={App} path="/">
<Route path="about" component={About} onLeave={handler} />
</Route>
);
routerWillLeave
class User extends React.Component {
static willTransitionFrom(transition) {
...
}
...
}
class User extends React.Component {
static routerWillLeave(nextState, router) {
...
}
...
}
State
static contextTypes = {
router: React.PropTypes.func,
}
render() {
const user = this.context.router.getCurrentParams().userId;
}
___
static contextTypes: {
location: React.Proptypes.object
}
render() {
const user = this.context.params.userId;
}
State on routing component
class User extends React.Component {
render() {
const location = this.props.location;
const params = this.props.params;
const history = this.props.history;
...
}
}
State
0.x 1.x
getPath() location.pathname +
location.query
getPathname() location.pathname
getParams() params
getQuery() location.query
getRoutes() routes
isActive(to, params,
query)
history.isActive(pathname,
query)
Questions?
slideshare.net/robgietema

Contenu connexe

Tendances (20)

Introduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace ITIntroduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace IT
 
React hooks
React hooksReact hooks
React hooks
 
React workshop presentation
React workshop presentationReact workshop presentation
React workshop presentation
 
React JS
React JSReact JS
React JS
 
reactJS
reactJSreactJS
reactJS
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
React js for beginners
React js for beginnersReact js for beginners
React js for beginners
 
Introduction to React
Introduction to ReactIntroduction to React
Introduction to React
 
React + Redux for Web Developers
React + Redux for Web DevelopersReact + Redux for Web Developers
React + Redux for Web Developers
 
React and redux
React and reduxReact and redux
React and redux
 
Its time to React.js
Its time to React.jsIts time to React.js
Its time to React.js
 
React js
React jsReact js
React js
 
React js - The Core Concepts
React js - The Core ConceptsReact js - The Core Concepts
React js - The Core Concepts
 
Reactjs
ReactjsReactjs
Reactjs
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
Introduction to react
Introduction to reactIntroduction to react
Introduction to react
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
React
React React
React
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 

En vedette

React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesomeAndrew Hull
 
Introduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic AppsIntroduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic AppsFederico Torre
 
Let's discover React and Redux with TypeScript
Let's discover React and Redux with TypeScriptLet's discover React and Redux with TypeScript
Let's discover React and Redux with TypeScriptMathieu Savy
 
Building Open-Source React Components
Building Open-Source React ComponentsBuilding Open-Source React Components
Building Open-Source React ComponentsZack Argyle
 
005. a React project structure
005. a React project structure005. a React project structure
005. a React project structureBinh Quan Duc
 
React.js in real world apps.
React.js in real world apps. React.js in real world apps.
React.js in real world apps. Emanuele DelBono
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJSAll Things Open
 
A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.jsDoug Neiner
 
Introduce flux & react in practice
Introduce flux & react in practiceIntroduce flux & react in practice
Introduce flux & react in practiceHsuan Fu Lien
 

En vedette (12)

React JS and why it's awesome
React JS and why it's awesomeReact JS and why it's awesome
React JS and why it's awesome
 
Introduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic AppsIntroduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic Apps
 
Let's discover React and Redux with TypeScript
Let's discover React and Redux with TypeScriptLet's discover React and Redux with TypeScript
Let's discover React and Redux with TypeScript
 
Building Open-Source React Components
Building Open-Source React ComponentsBuilding Open-Source React Components
Building Open-Source React Components
 
005. a React project structure
005. a React project structure005. a React project structure
005. a React project structure
 
003. ReactJS basic
003. ReactJS basic003. ReactJS basic
003. ReactJS basic
 
React.js in real world apps.
React.js in real world apps. React.js in real world apps.
React.js in real world apps.
 
An Introduction to ReactJS
An Introduction to ReactJSAn Introduction to ReactJS
An Introduction to ReactJS
 
A Brief Introduction to React.js
A Brief Introduction to React.jsA Brief Introduction to React.js
A Brief Introduction to React.js
 
React js
React jsReact js
React js
 
React lecture
React lectureReact lecture
React lecture
 
Introduce flux & react in practice
Introduce flux & react in practiceIntroduce flux & react in practice
Introduce flux & react in practice
 

Similaire à React Router: The Complete Guide

Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0Eyal Vardi
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverSpike Brehm
 
Server Side Swift with Swag
Server Side Swift with SwagServer Side Swift with Swag
Server Side Swift with SwagJens Ravens
 
Make your App Frontend Compatible
Make your App Frontend CompatibleMake your App Frontend Compatible
Make your App Frontend CompatibleOdoo
 
Creating an Uber Clone - Part XXIX - Transcript.pdf
Creating an Uber Clone - Part XXIX - Transcript.pdfCreating an Uber Clone - Part XXIX - Transcript.pdf
Creating an Uber Clone - Part XXIX - Transcript.pdfShaiAlmog1
 
ASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & ActionsASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & Actionsonsela
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationEyal Vardi
 
How to navigate programmatically using react router
How to navigate programmatically using react routerHow to navigate programmatically using react router
How to navigate programmatically using react routerBOSC Tech Labs
 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxVisual Engineering
 
Thinking metrics on React apps
Thinking metrics on React appsThinking metrics on React apps
Thinking metrics on React appsJean Carlo Emer
 
Emberjs building-ambitious-web-applications
Emberjs building-ambitious-web-applicationsEmberjs building-ambitious-web-applications
Emberjs building-ambitious-web-applicationsColdFusionConference
 
How to implement multiple layouts using React router V4.pptx
How to implement multiple layouts using React router V4.pptxHow to implement multiple layouts using React router V4.pptx
How to implement multiple layouts using React router V4.pptxBOSC Tech Labs
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsMihail Gaberov
 
Intro to React | DreamLab Academy
Intro to React | DreamLab AcademyIntro to React | DreamLab Academy
Intro to React | DreamLab AcademyDreamLab
 

Similaire à React Router: The Complete Guide (20)

Http Communication in Angular 2.0
Http Communication in Angular 2.0Http Communication in Angular 2.0
Http Communication in Angular 2.0
 
Introducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and serverIntroducing Rendr: Run your Backbone.js apps on the client and server
Introducing Rendr: Run your Backbone.js apps on the client and server
 
Server Side Swift with Swag
Server Side Swift with SwagServer Side Swift with Swag
Server Side Swift with Swag
 
Node.js server-side rendering
Node.js server-side renderingNode.js server-side rendering
Node.js server-side rendering
 
Meteor iron:router
Meteor iron:routerMeteor iron:router
Meteor iron:router
 
Make your App Frontend Compatible
Make your App Frontend CompatibleMake your App Frontend Compatible
Make your App Frontend Compatible
 
Creating an Uber Clone - Part XXIX - Transcript.pdf
Creating an Uber Clone - Part XXIX - Transcript.pdfCreating an Uber Clone - Part XXIX - Transcript.pdf
Creating an Uber Clone - Part XXIX - Transcript.pdf
 
ASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & ActionsASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & Actions
 
Sessi
SessiSessi
Sessi
 
Angular 2.0 Routing and Navigation
Angular 2.0 Routing and NavigationAngular 2.0 Routing and Navigation
Angular 2.0 Routing and Navigation
 
How to navigate programmatically using react router
How to navigate programmatically using react routerHow to navigate programmatically using react router
How to navigate programmatically using react router
 
Workshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & ReduxWorkshop 20: ReactJS Part II Flux Pattern & Redux
Workshop 20: ReactJS Part II Flux Pattern & Redux
 
Express JS
Express JSExpress JS
Express JS
 
Angular routing
Angular routingAngular routing
Angular routing
 
Thinking metrics on React apps
Thinking metrics on React appsThinking metrics on React apps
Thinking metrics on React apps
 
Emberjs building-ambitious-web-applications
Emberjs building-ambitious-web-applicationsEmberjs building-ambitious-web-applications
Emberjs building-ambitious-web-applications
 
How to implement multiple layouts using React router V4.pptx
How to implement multiple layouts using React router V4.pptxHow to implement multiple layouts using React router V4.pptx
How to implement multiple layouts using React router V4.pptx
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIs
 
ES2015 Modules
ES2015 ModulesES2015 Modules
ES2015 Modules
 
Intro to React | DreamLab Academy
Intro to React | DreamLab AcademyIntro to React | DreamLab Academy
Intro to React | DreamLab Academy
 

Plus de Rob Gietema

Van klimhal naar Big Wall: Bergsportdag 2024
Van klimhal naar Big Wall: Bergsportdag 2024Van klimhal naar Big Wall: Bergsportdag 2024
Van klimhal naar Big Wall: Bergsportdag 2024Rob Gietema
 
Alpiene Cursussen van Bergsportreizen: Bergsportdag 2024
Alpiene Cursussen van Bergsportreizen: Bergsportdag 2024Alpiene Cursussen van Bergsportreizen: Bergsportdag 2024
Alpiene Cursussen van Bergsportreizen: Bergsportdag 2024Rob Gietema
 
How to Build a Site Using Nick
How to Build a Site Using NickHow to Build a Site Using Nick
How to Build a Site Using NickRob Gietema
 
Nick: A Nearly Headless CMS
Nick: A Nearly Headless CMSNick: A Nearly Headless CMS
Nick: A Nearly Headless CMSRob Gietema
 
Van Klimhal naar Big Wall
Van Klimhal naar Big WallVan Klimhal naar Big Wall
Van Klimhal naar Big WallRob Gietema
 
Van 0 naar 6000+
Van 0 naar 6000+Van 0 naar 6000+
Van 0 naar 6000+Rob Gietema
 
How to create your own Volto site!
How to create your own Volto site!How to create your own Volto site!
How to create your own Volto site!Rob Gietema
 
Volto Extensibility Story: Plone Conference 2018
Volto Extensibility Story: Plone Conference 2018Volto Extensibility Story: Plone Conference 2018
Volto Extensibility Story: Plone Conference 2018Rob Gietema
 
Volto: Plone Conference 2018
Volto: Plone Conference 2018Volto: Plone Conference 2018
Volto: Plone Conference 2018Rob Gietema
 
React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15Rob Gietema
 
React Native: React Meetup 3
React Native: React Meetup 3React Native: React Meetup 3
React Native: React Meetup 3Rob Gietema
 
Four o Four: World Plone Day 2014
Four o Four: World Plone Day 2014Four o Four: World Plone Day 2014
Four o Four: World Plone Day 2014Rob Gietema
 
Hackathon: Silicon Alley Lightning Talks
Hackathon: Silicon Alley Lightning TalksHackathon: Silicon Alley Lightning Talks
Hackathon: Silicon Alley Lightning TalksRob Gietema
 
Resource Registries: Plone Conference 2014
Resource Registries: Plone Conference 2014Resource Registries: Plone Conference 2014
Resource Registries: Plone Conference 2014Rob Gietema
 
Arnhem Sprint 2013: Plone Conference 2013
Arnhem Sprint 2013: Plone Conference 2013Arnhem Sprint 2013: Plone Conference 2013
Arnhem Sprint 2013: Plone Conference 2013Rob Gietema
 
Plone 5: Nederlandse Plone Gebruikersdag 2014
Plone 5: Nederlandse Plone Gebruikersdag 2014Plone 5: Nederlandse Plone Gebruikersdag 2014
Plone 5: Nederlandse Plone Gebruikersdag 2014Rob Gietema
 
Projectgroep Millennium GroenLinks Arnhem
Projectgroep Millennium GroenLinks ArnhemProjectgroep Millennium GroenLinks Arnhem
Projectgroep Millennium GroenLinks ArnhemRob Gietema
 
Deco UI: Plone Conference 2010
Deco UI: Plone Conference 2010Deco UI: Plone Conference 2010
Deco UI: Plone Conference 2010Rob Gietema
 
Deco UI: DZUG Tagung 2010
Deco UI: DZUG Tagung 2010Deco UI: DZUG Tagung 2010
Deco UI: DZUG Tagung 2010Rob Gietema
 
Deco UI: Nederlandse Plone Gebruikesdag 2010
Deco UI: Nederlandse Plone Gebruikesdag 2010Deco UI: Nederlandse Plone Gebruikesdag 2010
Deco UI: Nederlandse Plone Gebruikesdag 2010Rob Gietema
 

Plus de Rob Gietema (20)

Van klimhal naar Big Wall: Bergsportdag 2024
Van klimhal naar Big Wall: Bergsportdag 2024Van klimhal naar Big Wall: Bergsportdag 2024
Van klimhal naar Big Wall: Bergsportdag 2024
 
Alpiene Cursussen van Bergsportreizen: Bergsportdag 2024
Alpiene Cursussen van Bergsportreizen: Bergsportdag 2024Alpiene Cursussen van Bergsportreizen: Bergsportdag 2024
Alpiene Cursussen van Bergsportreizen: Bergsportdag 2024
 
How to Build a Site Using Nick
How to Build a Site Using NickHow to Build a Site Using Nick
How to Build a Site Using Nick
 
Nick: A Nearly Headless CMS
Nick: A Nearly Headless CMSNick: A Nearly Headless CMS
Nick: A Nearly Headless CMS
 
Van Klimhal naar Big Wall
Van Klimhal naar Big WallVan Klimhal naar Big Wall
Van Klimhal naar Big Wall
 
Van 0 naar 6000+
Van 0 naar 6000+Van 0 naar 6000+
Van 0 naar 6000+
 
How to create your own Volto site!
How to create your own Volto site!How to create your own Volto site!
How to create your own Volto site!
 
Volto Extensibility Story: Plone Conference 2018
Volto Extensibility Story: Plone Conference 2018Volto Extensibility Story: Plone Conference 2018
Volto Extensibility Story: Plone Conference 2018
 
Volto: Plone Conference 2018
Volto: Plone Conference 2018Volto: Plone Conference 2018
Volto: Plone Conference 2018
 
React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15React Native: JS MVC Meetup #15
React Native: JS MVC Meetup #15
 
React Native: React Meetup 3
React Native: React Meetup 3React Native: React Meetup 3
React Native: React Meetup 3
 
Four o Four: World Plone Day 2014
Four o Four: World Plone Day 2014Four o Four: World Plone Day 2014
Four o Four: World Plone Day 2014
 
Hackathon: Silicon Alley Lightning Talks
Hackathon: Silicon Alley Lightning TalksHackathon: Silicon Alley Lightning Talks
Hackathon: Silicon Alley Lightning Talks
 
Resource Registries: Plone Conference 2014
Resource Registries: Plone Conference 2014Resource Registries: Plone Conference 2014
Resource Registries: Plone Conference 2014
 
Arnhem Sprint 2013: Plone Conference 2013
Arnhem Sprint 2013: Plone Conference 2013Arnhem Sprint 2013: Plone Conference 2013
Arnhem Sprint 2013: Plone Conference 2013
 
Plone 5: Nederlandse Plone Gebruikersdag 2014
Plone 5: Nederlandse Plone Gebruikersdag 2014Plone 5: Nederlandse Plone Gebruikersdag 2014
Plone 5: Nederlandse Plone Gebruikersdag 2014
 
Projectgroep Millennium GroenLinks Arnhem
Projectgroep Millennium GroenLinks ArnhemProjectgroep Millennium GroenLinks Arnhem
Projectgroep Millennium GroenLinks Arnhem
 
Deco UI: Plone Conference 2010
Deco UI: Plone Conference 2010Deco UI: Plone Conference 2010
Deco UI: Plone Conference 2010
 
Deco UI: DZUG Tagung 2010
Deco UI: DZUG Tagung 2010Deco UI: DZUG Tagung 2010
Deco UI: DZUG Tagung 2010
 
Deco UI: Nederlandse Plone Gebruikesdag 2010
Deco UI: Nederlandse Plone Gebruikesdag 2010Deco UI: Nederlandse Plone Gebruikesdag 2010
Deco UI: Nederlandse Plone Gebruikesdag 2010
 

Dernier

'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...APNIC
 
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130  Available With RoomVIP Kolkata Call Girl Kestopur 👉 8250192130  Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Roomdivyansh0kumar0
 
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersDamian Radcliffe
 
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With RoomVIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Roomgirls4nights
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024APNIC
 
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxAWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxellan12
 
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...SofiyaSharma5
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsThierry TROUIN ☁
 
Gram Darshan PPT cyber rural in villages of india
Gram Darshan PPT cyber rural  in villages of indiaGram Darshan PPT cyber rural  in villages of india
Gram Darshan PPT cyber rural in villages of indiaimessage0108
 
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...Sheetaleventcompany
 
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Delhi Call girls
 
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts servicesonalikaur4
 
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebJames Anderson
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 

Dernier (20)

Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
'Future Evolution of the Internet' delivered by Geoff Huston at Everything Op...
 
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
 
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130  Available With RoomVIP Kolkata Call Girl Kestopur 👉 8250192130  Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
 
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
 
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With RoomVIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
 
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
 
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxAWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
 
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with Flows
 
Gram Darshan PPT cyber rural in villages of india
Gram Darshan PPT cyber rural  in villages of indiaGram Darshan PPT cyber rural  in villages of india
Gram Darshan PPT cyber rural in villages of india
 
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
 
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
 
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
 
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark WebGDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
GDG Cloud Southlake 32: Kyle Hettinger: Demystifying the Dark Web
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
 

React Router: The Complete Guide

  • 1. React Router React Meetup XXL - September 23, 2015 -Rob Gietema @robgietema
  • 4. Routing url to React Component Route /aboutto <About /> Route /user/1234to <User /> Route /user/1234?message=Hito <User />
  • 5. Michael Jackson & Ryan Florence
  • 6. 2.002 commits 53 releases 197 contributors 180k downloads / month
  • 7. What does it look like?
  • 9. Simple example import { Route } from 'react-router'; const routes = ( <Route handler={App} path="/"> <Route name="about" handler={About} /> </Route> ); About page is available at /about
  • 10. Using custom path import { Route } from 'react-router'; const routes = ( <Route handler={App} path="/"> <Route name="about" path="my-about" handler={About} /> </Route> ); About page is available at /my-about
  • 11. Default route import { Route, DefaultRoute } from 'react-router'; const routes = ( <Route handler={App} path="/"> <DefaultRoute handler={Home} /> <Route name="about" handler={About} /> </Route> ); Home is available at /
  • 12. Not found route import { Route, NotFoundRoute } from 'react-router'; const routes = ( <Route handler={App} path="/"> <Route name="about" handler={About} /> <NotFoundRoute handler={NotFound}/> </Route> );
  • 13. Nesting import { Route } from 'react-router'; const routes = ( <Route handler={App} path="/"> <Route name="users" handler={Users}> <Route name="recent-users" path="recent" handler={RecentUsers} /> </Route> </Route> ); Recent users available at /users/recent
  • 14. Params import { Route } from 'react-router'; const routes = ( <Route handler={App} path="/"> <Route name="users" handler={Users}> <Route name="user" path="/user/:userId" handler={User} /> </Route> </Route> ); User 1234is available at /user/1234
  • 15. Multiple params import { Route } from 'react-router'; const routes = ( <Route handler={App} path="/"> <Route name="users" handler={Users}> <Route name="user-message" path="/user/:userId/message/:messageId" handler={User} /> </Route> </Route> ); Example /users/123/message/456
  • 16. Redirect routes import { Route, Redirect } from 'react-router'; const routes = ( <Route handler={App} path="/"> <Route name="about" handler={About} /> <Redirect from="company" to="about" /> </Route> ); /companywill be redirected to /about
  • 17. Redirect routes with params import { Route, Redirect } from 'react-router'; const routes = ( <Route handler={App} path="/"> <Redirect from="/user/me" to="user" params={{userId: MY_ID}} /> <Route name="user" path="/user/:userId" handler={User} /> </Route> ); Notice the order of the routes
  • 18. Without nesting import { Route, Redirect } from 'react-router'; const routes = [ <Route name="about" handler={About} />, <Route name="contact" handler={Contact} /> ]; Array of routes
  • 19. Include external routes import { Route, Redirect } from 'react-router'; import aboutRoutes from 'about/routes'; const routes = { <Route handler={App} path="/"> <Redirect from="/user/me" to="user" params={{userId: MY_ID}} /> <Route name="user" path="/user/:userId" handler={User} /> {aboutRoutes} </Route> };
  • 21. Using hashes import React from 'react'; import Router from 'react-router'; Router.run(routes, (Handler) => { React.render(<Handler/>, document.body); }); Location will be http://localhost/#/aboutetc.
  • 22. Using HTML5 History import React from 'react'; import Router from 'react-router'; Router.run(routes, Router.HistoryLocation, (Handler) => { React.render(<Handler/>, document.body); }); Location will be http://localhost/aboutetc.
  • 23. Using Universal Rendering import React from 'react'; import Router from 'react-router'; app.serve((req, res) => { Router.run(routes, req.path, function (Handler) { const html = React.renderToString(Handler); res.send(html); }); }); Render html to the client
  • 25. App component import React from 'react'; import { RouterHandler } from 'react-router'; class App extends React.Component { render() { return ( <div> <h1>Hello World!</h1> <RouterHandler /> </div> ); } } Use RouterHandlerto render matched route
  • 27. ES5 import React from 'react'; var User = React.createClass({ contextTypes: { router: React.PropTypes.func }, render: function () { return <h1>Hello World</h1>; } } Available in render self.context.router
  • 28. ES6 import React from 'react'; class User extends React.Component { render() { return <h1>Hello World</h1>; } } User.contextTypes = { router: React.PropTypes.func }; Available in render self.context.router
  • 29. ES7 import React from 'react'; class User extends React.Component { static contextTypes = { router: React.PropTypes.func, } render() { return <h1>Hello World</h1>; } } Available in render self.context.router
  • 31. Getting params import React from 'react'; class User extends React.Component { static contextTypes = { router: React.PropTypes.func, } render() { const user = this.context.router.getCurrentParams().userId; return <h1>Hello user {user}</h1>; } } From route /user/:userId
  • 32. Getting query params import React from 'react'; class User extends React.Component { static contextTypes = { router: React.PropTypes.func, } render() { const message = this.context.router.getCurrentQuery().message; return <h1>{message}</h1>; } } From url /user/1234?message=Hello%20World
  • 33. Getting current routes import React from 'react'; class User extends React.Component { static contextTypes = { router: React.PropTypes.func, } render() { const routes = this.context.router.getCurrentRoutes(); ... } } Array of routes in nesting order
  • 34. Fetching data import React from 'react'; import Router from 'react-router'; Router.run(routes, (Handler, state) => { fetchData(state).then(() => { React.render(<Handler/>, document.body); }); });
  • 35. Fetching data function fetchData(state) { return Promise.all(state.routes.filter((route) => { return route.handler.fetchData; }).map((route) => { return route.handler.fetchData(state.params, state.query); }); }
  • 36. Fetching data import React from 'react'; class User extends React.Component { static fetchData(params) { return new Promise((resolve) => { MyApi.loadSomething(() => { resolve(); }); }); } ... }
  • 37. isActive method import React from 'react'; class Tab extends React.Component { static contextTypes = { router: React.PropTypes.func, } render() { const isActive = this.isActive(this.props.to); const className = isActive ? 'active' : ''; return <li className={className}><Link {...this.props} />; } } Call with <Tab to="about">About</Tab>
  • 39. Using href import React from 'react'; class User extends React.Component { render() { return ( <a href="/about">About</a> ); } } Don't use this!
  • 40. Using Link Component import React from 'react'; import { Link } from 'react-router'; class User extends React.Component { render() { return ( <Link to="about">About</Link> ); } } Will generate <a href="/about">About</a>
  • 41. Using Link Component import React from 'react'; import { Link } from 'react-router'; class About extends React.Component { render() { return ( <Link to="user" params={{userId: 1234}}>User 1234</Link> ); } } With params
  • 42. Using Link Component import React from 'react'; import { Link } from 'react-router'; class About extends React.Component { render() { return ( <Link to="contact" query={{message: 'Hi'}}>Say hi</Link> ); } } Will generate /contact?message=Hi
  • 43. Using makeHref import React from 'react'; class User extends React.Component { static contextTypes = { router: React.PropTypes.func, } render() { const link = this.context.router.makeHref('about'); return ( <a href={link}>About</a> ); } }
  • 44. Using makeHref import React from 'react'; class About extends React.Component { static contextTypes = { router: React.PropTypes.func, } render() { const link = this.context.router.makeHref('user', { userId: 1234 }, { message: 'Hi'}); return ( <a href={link}>About</a> ); } } With params and query params
  • 45. Using transitionTo import React from 'react'; class User extends React.Component { static contextTypes = { router: React.PropTypes.func, } onSubmit() { this.context.router.transitionTo('about'); } ... } Will transition to /about
  • 46. Using transitionTo import React from 'react'; class About extends React.Component { static contextTypes = { router: React.PropTypes.func, } onSubmit() { this.context.router.transitionTo('user', {userId: 1234}); } ... } Will transition to /user/1234
  • 47. Using transitionTo import React from 'react'; class About extends React.Component { static contextTypes = { router: React.PropTypes.func, } onSubmit() { this.context.router.transitionTo('contact', {}, {message: 'Hi'}); } ... } Will transition to /contact?message=Hi
  • 48. Using replaceWith import React from 'react'; class User extends React.Component { static contextTypes = { router: React.PropTypes.func, } onSubmit() { this.context.router.replaceWith('about'); } ... } Not added to browser history
  • 49. Using goBack import React from 'react'; class About extends React.Component { static contextTypes = { router: React.PropTypes.func, } onClick() { this.context.router.goBack(); } ... } Go back one step in history
  • 50. goForward import React from 'react'; class About extends React.Component { static contextTypes = { router: React.PropTypes.func, } onClick() { this.context.router.goForward(); } ... } Go forward one step in history
  • 51. go(n) import React from 'react'; class About extends React.Component { static contextTypes = { router: React.PropTypes.func, } onClick() { this.context.router.go(2); } ... } Go forward two steps in history
  • 52. go(-n) import React from 'react'; class About extends React.Component { static contextTypes = { router: React.PropTypes.func, } onClick() { this.context.router.go(-2); } ... } Go backward two steps in history
  • 54. willTransitionTo import React from 'react'; class User extends React.Component { static willTransitionTo(transition) { if (!auth.loggedIn()) { transition.redirect('/login', {}, {'redirect' : transition.path}); } } ... }
  • 55. willTransitionFrom import React from 'react'; class User extends React.Component { static willTransitionFrom(transition) { if (!form.validate()) { transition.abort(); } } ... }
  • 57. Handler to component import { Route } from 'react-router'; const routes = ( <Route handler={App} path="/"> <Route name="about" handler={About} /> </Route> ); ... const routes = ( <Route component={App} path="/"> <Route path="about" component={About} /> </Route> );
  • 58. RouterHandler to props class App extends React.Component { render() { return ( <RouterHandler /> ); } } class App extends React.Component { render() { return ( {this.props.children} ); } }
  • 59. No more named routes <Route handler={App} path="/"> <Route name="user" path="/user/:userId" handler={User} /> </Route> ... <Route component={App} path="/"> <Route path="/user/:userId" component={User} /> </Route>
  • 60. Not found route <NotFoundRoute handler={NotFound} /> ... <Route path="*" component={NotFound} /> Catch all
  • 61. Redirect routes <Route handler={App} path="/"> <Redirect from="/user/me" to="user" params={userId: '1234'} /> <Route name="user" path="/user/:userId" handler={User} /> </Route> ... <Route component={App} path="/"> <Redirect from="/user/me" to="/user/1234" /> <Route path="/user/:userId" component={User} /> </Route> Params in the url
  • 62. Default route <Route handler={App} path="/"> <DefaultRoute handler={Home} /> <Route name="about" handler={About} /> </Route> ... <Route component={App} path="/"> <IndexRoute component={Home} /> <Route path="about" component={About} /> </Route> Home is available at /
  • 63. Multiple components import { Route } from 'react-router'; const routes = ( <Route component={App}> <Route path="users" components={{main: Users, sidebar: UsersSidebar}}/> </Route> );
  • 64. Multiple components import React from 'react'; class App extends React.Component { render() { return ( <div> <div className="Main"> {this.props.main} </div> <div className="Sidebar"> {this.props.sidebar} </div> </div> ); } }
  • 65. Running the router Router.run(routes, (Handler) => { React.render(<Handler/>, document.body); }); ... import { history } from 'react-router/lib/HashHistory'; React.render(( <Router history={history}> {routes} </Router> ), document.body);
  • 66. History options import { history } from 'react-router/lib/HashHistory'; import { history } from 'react-router/lib/BrowserHistory'; import { history } from 'react-router/lib/MemoryHistory';
  • 67. Using makeHref const link = this.context.router.makeHref('user', { userId: 1234 }, { message: 'Hi'}); ... const link = this.context.router.createHref('/user/1234', { message: 'Hi'}); Params in the link
  • 68. Link component <Link to="user" params={{userId: MY_ID}}>John Do</Link> ... <Link to={'/users/' + MY_ID}>John Do</Link> Params in the link
  • 69. transitionTo this.context.router.transitionTo(pathname, params, query) this.context.router.transitionTo('user', { userId: 1234 }, { message: 'Hi' }); ... this.context.router.transitionTo(pathname, query, state) this.context.router.transitionTo('/user/1234', { message: 'Hi' });
  • 70. willTransitionTo to onEnter class User extends React.Component { static willTransitionTo(transition) { ... } } ___ function requireAuth(nextState, transition) { ... } const routes = ( <Route component={App} path="/"> <Route path="about" component={About} onEnter={requireAuth} /> </Route> );
  • 71. willTransitionFrom to onLeave class User extends React.Component { static willTransitionFrom(transition) { ... } } ___ function handler(nextState, transition) { ... } const routes = ( <Route component={App} path="/"> <Route path="about" component={About} onLeave={handler} /> </Route> );
  • 72. routerWillLeave class User extends React.Component { static willTransitionFrom(transition) { ... } ... } class User extends React.Component { static routerWillLeave(nextState, router) { ... } ... }
  • 73. State static contextTypes = { router: React.PropTypes.func, } render() { const user = this.context.router.getCurrentParams().userId; } ___ static contextTypes: { location: React.Proptypes.object } render() { const user = this.context.params.userId; }
  • 74. State on routing component class User extends React.Component { render() { const location = this.props.location; const params = this.props.params; const history = this.props.history; ... } }
  • 75. State 0.x 1.x getPath() location.pathname + location.query getPathname() location.pathname getParams() params getQuery() location.query getRoutes() routes isActive(to, params, query) history.isActive(pathname, query)