React.js Intro

A JAVASCRIPT LIBRARY FOR BUILDING USER INTERFACES

  • The V in MVC on steroids
  • Virtual DOM (React abstracts away the DOM from you, giving a simpler programming model and better performance)
  • Data Flow (React implements one-way reactive data flow which reduces boilerplate and is easier to reason about than traditional data binding)

In React, data flows from owner to owned component through props as discussed above. This is effectively one-way data binding: owners bind their owned component's props to some value the owner has computed based on its props or state. Since this process happens recursively, data changes are automatically reflected everywhere they are used.

Pluses

  • Easy to learn
  • React enables the creation of UI components instead of templates. Components can be nested, they are reusable and encapsulated.
  • It changes the equation on how the DOM is updated and the cost to client-side rendering is significantly lower. It does that by:
    • Manages your event handlers for you, ensuring they're attached and detached at the correct time and on the correct nodes;
    • Creates and destroys DOM structures efficiently;
    • Uses virtual DOM diffing to determine which parts of a component have changed and only updates those parts.

The bare minimum and mandatory

Example

  • React.render(<Component/>,DOMelement) method
  • React.createClass({})
  • render method
  • Use react-tools nodejs module to compile the JSX code
$ jsx /source /destination
built Module("Main")
["App","Main"]
                  

HTML and JSX

What's this treachery? Peppering JS with HMTL? Noooo!!

  1. When reactjs is used with require, you can use this pattern for separating the template jsx
    Example (Stackoverflow)

The most important stuff

  • Props (this.props)
  • State (this.state)
  • Component Refs (this.refs)
  • The importance of keys
  • Component Life Cycle methods

Props

  • Props are great to pass data from parent component to nested components
  • Use for static data
  • propTypes method is used to validate the props and to make sure the component is used correctly

Example

              
                var Field = React.createClass({
                    render: function() {
                      return (<p>
                                  <label>{this.props.children}</label>
                                  <input type="text" value="" />
                                </p>
                      );
                   }
                });
                var Form = React.createClass({
                    fields: [
                        {
                            field1: 'First Name'
                        },
                        {
                            fields2: 'Last Name'
                        }
                    ],
                    renderFields: function(value, i) {
                        return (
                            <Field 
                                index={i}
                                >{value}</Field>
                        );
                    },
                    render: function() {
                        return (<div className="form">
                            {this.fields.map(this.renderFields)}
                            More props children
                            </div>
                        );
                    }
                });
                React.render(<Form maxCount={5} maxLength={20}/>,
                    document.getElementById('formContainer'));

              
            

State

Each component can have a state. When the state changes, render method is automatically triggered, so use state components that need a UI update. If a component does not change, keep it stateless. Use props instead.

  • getInitialState method runs only one time at the beginning of the life cycle of the component
  • setState(data, callback) method is used to update the state. Callback function is called after render method executes

Example with props only (stateless). When updating an amount input, its adjacent paragraph in table component does not update.

Example with state and props. The Table component now store the data received from form in state. Now the paragraphs update when the input values change. To fine tune the updating of the paragraphs, shouldComponentUpdate method was updated to check old state versus new state. Comment and uncomment shouldComponentUpdate method in js/Table.js line 35 to see how each paragraph updates.

Component Refs

Component Refs is a way to target a specific element within a component.

New Year and New Amount field values are captured via refs in this example

              
                var newYearValue = this.refs.newYear.getDOMNode().value
                    , newAmountValue = this.refs.newAmount.getDOMNode().value
                    ;
              
            
              
                <p><input className="newYear" ref="newYear" defaultValue="Year" type="text"/> 
                    <input className="newAmount" ref="newAmount" defaultValue="Amount" type="text"/> 
                    <button className="add-btn" onClick={this.addNewYear}>Add New Year</button>
                </p>
              
            

The importance of keys

Keys to Reactjs virtual DOM are what IDs are to DOM.

Keys are used for children components reconciliation. Normally Reactjs reconciles children in the order of rendering. This becomes problemating when the children are shuffled around as in search results or if new components are added on top of the list. Keys will solve this problem.

Keys have to be unique within the component only.
Long live encapsulation!

Component Life Cycle methods

4 possible scenarios

  • Initial
  • Updating State
  • Updating Props
  • Unmounting

Example. Check out console logs outputted by child Table component and all the inline comments. Various methods are executed in specific order in a component's lifecycle.

Initial cycle

Except render method, all the other methods will execute only once in the life time of a component.

  1. getDefaultProps
  2. getInitialState
  3. componentWillMount
  4. render
  5. componentDidMount

Updating State cycle

If shouldComponentUpdate method returns false, render will be skipped.

  1. shouldComponentUpdate: function(nextProps, nextState) (boolean)
  2. componentWillUpdate
  3. render
  4. componentDidUpdate

Updating Props cycle

Use componentWillRecieveProps to change the state. There is no analogous method componentWillReceiveState.

An incoming prop transition may cause a state change,
but the opposite is not true.

  1. componentWillRecieveProps: function(nextProps) {} (opportunity to setState)
  2. shouldComponentUpdate: function(nextProps, nextState)
  3. componentWillUpdate
  4. render
  5. componentDidUpdate

Unmounting cycle

This method is invoked immediately before a component is unmounted from the DOM. It is used to do any necessary clean up in the page.

  1. componentWillUnmount

Links

The easiest way to learn React is to start with Linda.com video
and then experiment with code.