SlideShare una empresa de Scribd logo
1 de 76
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
洪 鹏发
 

La actualidad más candente (20)

React and redux
React and reduxReact and redux
React and redux
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
Reactjs
Reactjs Reactjs
Reactjs
 
ReactJS
ReactJSReactJS
ReactJS
 
React.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOMReact.js - The Dawn of Virtual DOM
React.js - The Dawn of Virtual DOM
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
React JS - Introduction
React JS - IntroductionReact JS - Introduction
React JS - Introduction
 
ES6 presentation
ES6 presentationES6 presentation
ES6 presentation
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
React for Beginners
React for BeginnersReact for Beginners
React for Beginners
 
React workshop
React workshopReact workshop
React workshop
 
React js for beginners
React js for beginnersReact js for beginners
React js for beginners
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
React
React React
React
 
Its time to React.js
Its time to React.jsIts time to React.js
Its time to React.js
 
Introduction to React
Introduction to ReactIntroduction to React
Introduction to React
 
Build web apps with react js
Build web apps with react jsBuild web apps with react js
Build web apps with react js
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 

Destacado

Destacado (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
 

Similar a React Router: React Meetup XXL

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
Spike Brehm
 
ASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & ActionsASP.NET MVC Controllers & Actions
ASP.NET MVC Controllers & Actions
onsela
 
Emberjs building-ambitious-web-applications
Emberjs building-ambitious-web-applicationsEmberjs building-ambitious-web-applications
Emberjs building-ambitious-web-applications
ColdFusionConference
 

Similar a React Router: React Meetup XXL (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
 

Más de Rob Gietema

Projectgroep Millennium GroenLinks Arnhem
Projectgroep Millennium GroenLinks ArnhemProjectgroep Millennium GroenLinks Arnhem
Projectgroep Millennium GroenLinks Arnhem
Rob Gietema
 

Más 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
 

Último

Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
soniya singh
 
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
Call Girls In Delhi Whatsup 9873940964 Enjoy Unlimited Pleasure
 
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Último (20)

Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Sarai Rohilla Escort Service Delhi N.C.R.
 
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting High Prof...
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting  High Prof...VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting  High Prof...
VIP Model Call Girls Hadapsar ( Pune ) Call ON 9905417584 Starting High Prof...
 
Russian Call Girls in %(+971524965298 )# Call Girls in Dubai
Russian Call Girls in %(+971524965298  )#  Call Girls in DubaiRussian Call Girls in %(+971524965298  )#  Call Girls in Dubai
Russian Call Girls in %(+971524965298 )# Call Girls in Dubai
 
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls DubaiDubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
Dubai=Desi Dubai Call Girls O525547819 Outdoor Call Girls Dubai
 
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
 
On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024
 
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
 
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
valsad Escorts Service ☎️ 6378878445 ( Sakshi Sinha ) High Profile Call Girls...
 
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Prashant Vihar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
(INDIRA) Call Girl Pune Call Now 8250077686 Pune Escorts 24x7
 
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
 
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
 
VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
 
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
 
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...Russian Call Girls Pune  (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
Russian Call Girls Pune (Adult Only) 8005736733 Escort Service 24x7 Cash Pay...
 
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
 
Call Now ☎ 8264348440 !! Call Girls in Rani Bagh Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Rani Bagh Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Rani Bagh Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Rani Bagh Escort Service Delhi N.C.R.
 
Russian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl ServiceRussian Call girl in Ajman +971563133746 Ajman Call girl Service
Russian Call girl in Ajman +971563133746 Ajman Call girl Service
 

React Router: React Meetup XXL

  • 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)