Share
Embed
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
Transcript
63 slides
-
What is this talk about? • Not about why React?!
• But what and how -
• A library by Facebook (now becoming an ecosystem) •
Mainly for View (i.e, UI and interaction, not logic) -
UI = Components The whole application is just a single
component which is a composition of various sub-components. -
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 -
One way data flow List ListItem numbers = [1,2,3] number=1
ListItem number=2 ListItem number=3 -
When interactions happen, React components reflect the changes by completely
re-rendering themselves. -
Benefits • Declarative UI (Your UI is a direct representation
of your state, no manual wiring) • Data In - Data Out -
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. -
Why is Virtual DOM so fast? • Lightweight • Highly
optimised diff algorithm • Batching Updates -
Summary • Composition of components • Declarative Rendering • One
way data flow • Complete re-rendering on Updates (Virtual DOM approach) -
var HelloWorld = React.createClass({ render: function() { return <h1> Hello
World!! </h1>; } }); ReactDOM.render( <HelloWorld />, document.getElementByTagName('body') ); Hello World -
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! -
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 -
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. -
Custom Components • Your application components are built as custom
component using built-in components. • Re-use them as if they were built-in components. -
// 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') ); -
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 -
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 -
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. -
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 -
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 -
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. -
var Counter = React.createClass({ getInitialState: function() { return { count:
0 } }, render: function() { return ( <p> { this.state.count } </p> ); } }); ReactDOM.render( <Counter />, document.getElementById('app') ); -
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 -
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. -
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 -
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. -
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 -
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 -
Simple Ajax Requests • Data is managed as the state
of container components. • Ajax calls are made within component lifecycle hooks. -
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 -
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 -
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. -
Let’s get real • A build system (Webpack) • ES6
transpiler (Babel) • A client-side router (react-router) • State Management (Redux) You are gonna need: -
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 )