Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.

React Router: React Meetup XXL

1.631 Aufrufe

Veröffentlicht am

React Router is the most widely used router for React, in use by almost half of all React projects. This talk is about using React Router in your project. It will start with the basics and will go through all features React Router has to offer in the current version and the upcoming 1.0 release. I will also go through some common problems including data fetching and authentication.

Veröffentlicht in: Internet
  • You can do this by using the history property (see: https://github.com/rackt/react-router/blob/master/UPGRADE_GUIDE.md#navigation-mixin).
       Antworten 
    Sind Sie sicher, dass Sie …  Ja  Nein
    Ihre Nachricht erscheint hier
  • Rob, thanks for your talk about react router yesterday. I'm having one little issue after using it (1.0-rc1): you pass the router down to components using context, but I have a feeling I'm missing out on a step here. I'm able to pass down the routes my app has (called AppRouter), but they don't have any .transitionTo methods etc. How would you suggest passing down an instance of the actual Router object to these components?
       Antworten 
    Sind Sie sicher, dass Sie …  Ja  Nein
    Ihre Nachricht erscheint hier

React Router: React Meetup XXL

  1. 1. React Router React Meetup XXL - September 23, 2015 -Rob Gietema @robgietema
  2. 2. Who am I?
  3. 3. What is react-router?
  4. 4. Routing url to React Component Route /aboutto <About /> Route /user/1234to <User /> Route /user/1234?message=Hito <User />
  5. 5. Michael Jackson & Ryan Florence
  6. 6. 2.002 commits 53 releases 197 contributors 180k downloads / month
  7. 7. What does it look like?
  8. 8. Defining routes
  9. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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> };
  20. 20. Running the router
  21. 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. 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. 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
  24. 24. Rendering the routes
  25. 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
  26. 26. Access router methods
  27. 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. 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. 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
  30. 30. Available router methods
  31. 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. 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. 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. 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. 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. 36. Fetching data import React from 'react'; class User extends React.Component { static fetchData(params) { return new Promise((resolve) => { MyApi.loadSomething(() => { resolve(); }); }); } ... }
  37. 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>
  38. 38. Navigating between routes
  39. 39. Using href import React from 'react'; class User extends React.Component { render() { return ( <a href="/about">About</a> ); } } Don't use this!
  40. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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
  53. 53. Lifecycle methods
  54. 54. willTransitionTo import React from 'react'; class User extends React.Component { static willTransitionTo(transition) { if (!auth.loggedIn()) { transition.redirect('/login', {}, {'redirect' : transition.path}); } } ... }
  55. 55. willTransitionFrom import React from 'react'; class User extends React.Component { static willTransitionFrom(transition) { if (!form.validate()) { transition.abort(); } } ... }
  56. 56. Changes in 1.0
  57. 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. 58. RouterHandler to props class App extends React.Component { render() { return ( <RouterHandler /> ); } } class App extends React.Component { render() { return ( {this.props.children} ); } }
  59. 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. 60. Not found route <NotFoundRoute handler={NotFound} /> ... <Route path="*" component={NotFound} /> Catch all
  61. 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. 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. 63. Multiple components import { Route } from 'react-router'; const routes = ( <Route component={App}> <Route path="users" components={{main: Users, sidebar: UsersSidebar}}/> </Route> );
  64. 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. 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. 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. 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. 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. 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. 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. 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. 72. routerWillLeave class User extends React.Component { static willTransitionFrom(transition) { ... } ... } class User extends React.Component { static routerWillLeave(nextState, router) { ... } ... }
  73. 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. 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. 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)
  76. 76. Questions? slideshare.net/robgietema

×