Upgrade to PRO for Only $50/Year—Limited-Time Offer! 🔥

React.js: An introduction

jjrofriloc
December 17, 2016

React.js: An introduction

This is a presentation given in Developer Conference Yangon 2016. An introduction to react.js and it's concepts.

jjrofriloc

December 17, 2016
Tweet

More Decks by jjrofriloc

Other Decks in Programming

Transcript

  1. • A library by Facebook (now becoming an ecosystem) •

    Mainly for View (i.e, UI and interaction, not logic)
  2. UI = Components The whole application is just a single

    component which is a composition of various sub-components.
  3. Components • Each component can has a set of properties.

    • Each component can has it’s own encapsulated state. • Encapsulated state is only concerned with the component itself. Parent components don’t need to know. • Eg. clock component’s current time
  4. Benefits • Declarative UI (Your UI is a direct representation

    of your state, no manual wiring) • Data In - Data Out
  5. Virtual DOM • An abstraction between the (real) DOM and

    React components. • It’s a light weight version of DOM which represents a React component tree. • Whenever there is change, React components render themselves as a Virtual DOM.
  6. Why is Virtual DOM so fast? • Lightweight • Highly

    optimised diff algorithm • Batching Updates
  7. Summary • Composition of components • Declarative Rendering • One

    way data flow • Complete re-rendering on Updates (Virtual DOM approach)
  8. var HelloWorld = React.createClass({ render: function() { return <h1> Hello

    World!! </h1>; } }); ReactDOM.render( <HelloWorld />, document.getElementByTagName('body') ); Hello World
  9. JSX • A speical syntax for react (imitated from HTML,

    not actual HTML) • `<h1> Hello World! </h1>` is transformed into `React.createElement( "h1", null, ” Hello World ");` • Why? Because HTML syntax is familiar and easy to read when nested. • Of course, you can choose not to use JSX. Up to you!
  10. var InvoiceTable = React.createClass({ render: function() { return ( <table>

    <thead> <tr> <th> Name </th> <th> Price </th> </tr> </thead> <tbody> <tr> <td>Beef</td> <td>2500 Ks</td> </tr> <tr> <td>Pork</td> <td>2000 Ks</td> </tr> </tbody> </table> ); } }); React.createElement( "table", null, React.createElement( "thead", null, React.createElement( "tr", null, React.createElement( "th", null, " Name " ), React.createElement( "th", null, " Price " ) ) ), React.createElement( "tbody", null, React.createElement( "tr", null, React.createElement( "td", null, "Beef" ), React.createElement( "td", null, "2500 Ks" ) ), React.createElement( "tr", null, React.createElement( "td", null, "Pork" ), React.createElement( "td", null, "2000 Ks" ) ) ) ); JSX vs Standard JS Objects
  11. Built-in Components • React gives you built-in components which generate

    normal html components. • `<h1>` is a built-in component. In fact, you can use any valid html tag as a built-in component.
  12. Custom Components • Your application components are built as custom

    component using built-in components. • Re-use them as if they were built-in components.
  13. // Using react-bootstrap component libraries // from https://react-bootstrap.github.io/components.html#jumbotron var HeroUnit

    = React.createClass({ render: function() { return ( <Jumbotron> <h1>Hello, world!</h1> <p>This is a simple hero unit, a simple jumbotron-style component for calling extra attention to featured content or information.</p> <p><Button bsStyle="primary">Learn more</Button></p> </Jumbotron> ); } }); ReactDOM.render( <HeroUnit />, document.getElementByTagName('body') );
  14. var HeroUnit = React.createClass({ render: function() { return ( <Jumbotron>

    <h1>{ this.props.heading }</h1> <p> { this.props.description } </p> <p><Button bsStyle="primary">Learn more</Button></p> </Jumbotron> ); } }); var propsDescription = "You can use props to pass any information down the component hierarchy. You can use any js types as props." ReactDOM.render( <HeroUnit heading={“Props are awesome”} description={propsDescription} />, document.getElementByTagName('body') ); Props in Action
  15. var HeroUnit = React.createClass({ render: function() { return ( <Jumbotron>

    <h1>{ this.props.heading }</h1> <p> { this.props.description } </p> <p><Button bsStyle="primary">Learn more</Button></p> </Jumbotron> ); } }); HeroUnit.propTypes = { heading: React.PropTypes.string, description: React.PropTypes.string }; var propsDescription = "You can use props to pass any information down the component hierarchy. You can use any js types as props." ReactDOM.render( <HeroUnit heading="Props are awesome" description={propsDescription} />, document.getElementByTagName('body') ); Defining PropTypes
  16. Every component is defined in Javascript. • Remember!? JSX is

    just javascript and we used JS expression for props. • So, you can use any javascript code to manipulate components. • This means: variables, loops, conditionals, functions can be used inside render function.
  17. var InvoiceTable = React.createClass({ render: function() { return ( <table>

    <thead> <tr> <th> Name </th> <th> Price </th> </tr> </thead> <tbody> { items.map(function(item){ return ( <tr> <td>{item.name}</td> <td>{item.price}</td> </tr> ); }) } </tbody> </table> ); } }); InvoiceTable.propTypes = { items: React.PropTypes.array } var items = [ { name: "Beef", price: 3000 }, { name: "Pork", price: 2000 } ] ReactDOM.render(<InvoiceTable items={items} />, document.getElementById('app')); Loops
  18. var Profile = React.createClass({ render: function () { var isLoggedIn

    = this.props.isLoggedIn; var button = null; if (isLoggedIn) { button = <LogoutButton />; } else { button = <LoginButton />; } return ( <div> <Greeting isLoggedIn={isLoggedIn} /> {button} </div> ); } }); ReactDOM.render( <Profile isLoggedIn={false} />, document.getElementById('app') ); Conditionals
  19. Components can have their own internal states. • Props are

    passed from parents. States are managed by the component itself. • State should not be concerned with external data. It should only be concerned with the component itself and nothing else. • Changing state causes re-rendering of the component. • State is created by defining getInitialState() and changed by using `this.setState()` within component.
  20. var Counter = React.createClass({ getInitialState: function() { return { count:

    0 } }, render: function() { return ( <p> { this.state.count } </p> ); } }); ReactDOM.render( <Counter />, document.getElementById('app') );
  21. Props Vs State • Props: data passed into the component

    or defaulted. Immutable from the component's perspective. • State: data that changes with user input, time, or server responses. State is mutable via this.setState. • Try to keep components stateless by using props whenever possible. • Push state to the top and pass state to child components as props. http://ad2games.github.io/presentations/reactjs.html#15
  22. Synthetic Event System • In react, DOM events are abstracted

    as a single event system by React, namely Synthetic Event System. • React defines a list of events on its own which wraps on top of DOM events. • Only Built-in components can listen to Synthetic Events.
  23. var ClickMe = React.createClass({ getInitialState: function() { return { clickedCount:

    0 }; }, handleClick: function() { //Event handler for click event this.setState({clickedCount: this.state.clickedCount + 1}) console.log("Clicked!", this.state.clickedCount); }, render: function() { return ( <div> <button onClick={this.handleClick}> Click me </button> <p> You clicked me { this.state.clickedCount } times </p> </div> ); } }); State and Event Working Together
  24. How to listen event on Custom Components?? • Accept a

    prop for event handler • Attach it to the underlying built-in component • Parent components can control child components behaviour that way.
  25. var CatList = React.createClass({ getInitialState: function() { return {cats: [{id:

    1, name: “Garfield”}, {id: 2, name: “Ji Ji”}], currentCat: 0}; }, _onClick: function(index) { console.log("Clicked on", index); this.setState({currentCat: index}); }, render: function() { return ( <ul> { this.state.cats.map( function(cat, index) { return ( <CatListItem key={cat.id} cat={cat} onClick={this._onClick.bind(this, index)}/> ); }.bind(this)) } </ul> ); } }); var CatListItem = React.createClass({ render: function() { return ( <li onClick={this.props.onClick}> {this.props.cat.name} </li> ); } }); Event Handling on Custom Components
  26. var NameForm = React.createClass({ getInitialState: function() { return {value: ‘’};

    }, handleChange: function (event) { this.setState({value: event.target.value}); }, handleSubmit: function (event) { alert('A name was submitted: ' + this.state.value); event.preventDefault(); }, render: function () { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" value={this.state.value} onChange={this.handleChange} /> </label> <input type="submit" value="Submit" /> </form> ); } }); Working with forms and inputs
  27. Simple Ajax Requests • Data is managed as the state

    of container components. • Ajax calls are made within component lifecycle hooks.
  28. Lifecycle Hooks • Hook methods to override • Each method

    is invoked at each stage of react component lifecycle from virtual DOM creation/ update/destruction to actual rendering to the real DOM creation/update/destruction. • Convenient helpers for leaky abstraction
  29. var App = React.createClass({ getInitialState: function() { return { collection:

    [], currentIndex: 0 }; }, componentDidMount() { $.get(‘https://someapi.com‘).done(function(data) { this.setState({collection: data.items}); }.bind(this)); }, handleItemClick: function(index, e) { this.setState({currentCatIndex: index}); }, render: function() { var content = null; if (this.state.collection.length > 0) { content = <div className="app-container"> <div className="grid-item"> <ListView cats={this.state.collection} handleItemClick={this.handleItemClick} /> </div> <div className="grid-item"> <DetailView url={this.state.cats[this.state.currentCatIndex].url} /> </div> </div>; } else { content = <LoadingIndicator />; } return content; } }); External Ajax calls within lifecycle hook
  30. Leaky Abstractions • Working inside the react flow is wonderful.

    • But real world is harsh. There will always be time you need to dig under the floor. • Lifecycle hooks are there to help you with that.
  31. Let’s get real • A build system (Webpack) • ES6

    transpiler (Babel) • A client-side router (react-router) • State Management (Redux) You are gonna need:
  32. Learn More img: http://image.slidesharecdn.com/2015-150409045423-conversion-gate01/95/react-tech-salon-42-638.jpg? cb=1428560032 An overview of react ecosystem

    - Rami Sayar (https:// www.youtube.com/watch?v=8yTb3J6_Hak) A collection of react resources 
 ( https://github.com/enaqx/awesome-react )