O slideshow foi denunciado.
Utilizamos seu perfil e dados de atividades no LinkedIn para personalizar e exibir anúncios mais relevantes. Altere suas preferências de anúncios quando desejar.

A full introductory guide to React

228 visualizações

Publicada em

From React basics to React server render.

Publicada em: Tecnologia
  • Seja o primeiro a comentar

A full introductory guide to React

  1. 1. A full introductory
 guide to React
  2. 2. Jean Emer @jcemer
 jcemer.com
  3. 3. Work&Co
 Digital Products
  4. 4. ***
  5. 5. 1of9 What is React for
  6. 6. React is a library for building modular and reusable user interfaces
  7. 7. It is good for webapps that has different states and also to define a styleguide
  8. 8. State management is the coordination of actions and its effects
  9. 9. http://material-ui.com
  10. 10. Styleguide is a good way to keep your project in shape
  11. 11. 2of9 What is a React component
  12. 12. class HelloMessage extends React.Component { render() { return ( <div> Hello {this.props.name} </div> ); } }
  13. 13. JSX is XML with JavaScript
  14. 14. class HelloMessage extends React.Component { render() { return React.createElement( "div", null, "Hello ", this.props.name ); } }
  15. 15. class Timer extends React.Component { constructor(props) { super(props); this.state = { seconds: 0 }; } tick() { this.setState(prevState => ({ seconds: prevState.seconds + 1 })); } componentDidMount() { this.interval = setInterval(() => this.tick(), 1000); } componentWillUnmount() { clearInterval(this.interval); } render() { return ( <div>Seconds: {this.state.seconds}</div> ); } } State management Life cycles HTML with states and props
  16. 16. A React component is props, states, and life cycle hooks together
  17. 17. React is declarative, there is no need to define the interface transitions
  18. 18. <div>Seconds: {this.state.seconds}</div> I want a <div> with the seconds inside. Do it!
  19. 19. The role of the Virtual DOM is to transform the render result in imperative DOM instructions
  20. 20. <div>Seconds: 1</div> From <div>Seconds: 2</div> To element.textContent = 'Seconds 2' Do
  21. 21. return ( <ReactCSSTransitionGroup transitionName='number' transitionEnterTimeout={200} transitionLeaveTimeout={200}> <div key={this.state.seconds}> Seconds: {this.state.seconds} </div> </ReactCSSTransitionGroup> ); https://reactjs.org/docs/animation.html
  22. 22. 3of9 How to setup 
 and build 
 React
  23. 23. ReactDOM.render( <Component any={data} />, document
 .getElementById(‘component-root') ); It renders a component in the document
  24. 24. There is at least the need of using Babel with Transform React JSX plugin
  25. 25. https://github.com/ facebookincubator/create-react-app
  26. 26. https://github.com/facebookincubator/create-react-app/blob/ master/packages/react-scripts/config/webpack.config.dev.js
  27. 27. 4of9 How to fetch data for a component
  28. 28. class ServerTime extends React.Component { constructor(props) { super(props); this.state = { time: 'Fetching' }; } componentDidMount() { axios.get('/time.json') .then(res => this.setState({ time: res.data.time })); } render() { return ( <div>{this.state.time}</div> ); } } Get a response and change the state
  29. 29. Fetch the data right before the component is mounted
  30. 30. But what happens if the component isn’t mounted anymore when the response arrives?
  31. 31. class ServerTime extends React.Component { constructor(props) { super(props); this.cancelToken = axios.CancelToken.source(); this.state = { time: 'Fetching' }; } componentDidMount() { axios.get('/time.json', { cancelToken: this.cancelToken.token }) .then(res => this.setState({ time: res.data.time })); } componentWillUnmount() { this.cancelToken.cancel('Operation canceled by the user.'); } render() { return ( <div>{this.state.time}</div> ); } } Cancel token
  32. 32. https://discuss.reactjs.org/t/cancel-async-fetch-on-unmount/3272/2
  33. 33. 5of9 How to share state between components
  34. 34. class ServerTime extends React.Component { constructor(props) { super(props); this.state = { time: 'Fetching' }; } componentDidMount() { /* Fetch server time */ } render() { return ( <div> <Header time={this.state.time} /> <Content time={this.state.time} /> <Footer time={this.state.time} /> </div> ); } } Send the time via prop to different components
  35. 35. User
  36. 36. User
  37. 37. Transporting a user through all the component tree is a boring job
  38. 38. window.user = { name: 'Jean' } All components can easily access the user But what happens 
 if the user login or logout
  39. 39. https://redux.js.org/
  40. 40. The state store keeps the user and can be connected to components
  41. 41. import { connect } from 'react-redux'; const mapStateToProps = state => ({ user: state.user }) export default connect(mapStateToProps)(Header); Maps the user to a prop
  42. 42. Login and logout are actions that change the state store
  43. 43. store.dispatch(fetchUserAction); this.props.dispatch(logoutAction); On app bootstrap Inside a connected component
  44. 44. https://daveceddia.com/how-does-redux-work/
  45. 45. 6of9 What is children, HOC, render prop, and more
  46. 46. All that will see 
 are techniques to 
 code reuse
  47. 47. function Content(props) { return ( <div className='content'> {props.children} </div> ); } <Content> <Article /> <Comments /> </Content> Usage Content is a generic box
  48. 48. Higher-Order Component is a function that takes a component and returns a new component React documentation
  49. 49. import { connect } from 'react-redux'; const mapStateToProps = state => ({ user: state.user }) export default connect(mapStateToProps)(Header); It’s a HOC
  50. 50. <UserProvider> {user => ( <Header {...this.props} user={user}/>
 )}
 </UserProvider> Function as child component function UserProvider(props) { return props.children(window.user); }
  51. 51. A render prop is a function prop that a component uses to know what to render https://cdb.reacttraining.com/use-a-render-prop-50de598f11ce
  52. 52. <UserProvider render={user => ( <Header {...this.props} user={user}/> )}/> Render is a prop that accepts a function to render
  53. 53. • Children • Function as Child Component • Higher-Order Component • Function (render) as Prop Component
  54. 54. const HelloWorld = () => (<div>Hello world</div>); React Stateless Functional Components
  55. 55. 7of9 A bit about performance
  56. 56. React is fast!
  57. 57. https://reactjs.org/docs/react-api.html#reactpurecomponent
  58. 58. class HelloMessage extends React.Component { render() { return ( <div> Hello {this.props.name} </div> ); } }
  59. 59. class HelloMessage extends React.PureComponent { render() { return ( <div> Hello {this.props.name} </div> ); } } Shallow compare
  60. 60. shouldComponentUpdate()
  61. 61. 8of9 How to route an application
  62. 62. const BasicExample = () => ( <Router> <div> <ul> <li><Link to="/">Home</Link></li> <li><Link to="/about">About</Link></li> <li><Link to="/topics">Topics</Link></li> </ul> <hr/> <Route exact path="/" component={Home}/> <Route path="/about" component={About}/> <Route path="/topics" component={Topics}/> </div> </Router> ) React Router code example
  63. 63. It can be very complex if you try to async load data and animate the transitions
  64. 64. ***
  65. 65. 9of9 How to run React on the server
  66. 66. ReactDOM.renderToString( <Component any={data} />
 );
  67. 67. React Router default routing is dynamic and it is hard to fetch data on the server because of that
  68. 68. https://crypt.codemancers.com/posts/2017-06-03-reactjs-server-side- rendering-with-router-v4-and-redux/
  69. 69. https://crypt.codemancers.com/posts/2017-06-03-reactjs-server-side- rendering-with-router-v4-and-redux/
  70. 70. https://zeit.co/blog/next
  71. 71. https://zeit.co/blog/next
  72. 72. ***
  73. 73. I hope it inspires you @jcemer Thank you!

×