Introduction to React

Jacek Rzeszutek

meet.js Katowice, 12.11.2014

JS library for building User Interfaces

What is React?

  • V in the MVC
  • one-way reactive data flow, re-render on every update
  • plays nicely with your stack
  • simplicity
  • readability
  • performance

Components

  • creation: React.createClass + component's render function
  • render: React.render(<component>, <mountingNode>)

  • Example 1
var Hello = React.createClass({
          render: function() {
              return <h1>Hello meet.js :)</h1>;
          }
      });
       
React.render(<Hello/>, document.getElementById("app"));

Benefits from components

  • good separation of concerns
  • reusable
  • composable
  • low coupling, high cohesion
  • Example 2

State

  • maintaining state is easy, each component is stateful
  • most useful methods: setState and getInitialState
  • Example 3

Communication between components

  • props used for communication "down"
  • callbacks passed through props used for communication "up"
  • Example 4

When render happens?

  • setState
  • forceUpdate
  • render in parent component happened
  • Example 5

Component lifecycle

  • getDefaultProps
  • getInitialState
  • componentWillMount
  • componentDidMount
  • componentWillUnmount
  • and few others...

JSX

var Hello = React.createClass({
          render: function() {
              return <div>
                            <h1>Hello</h1>
                            <h2>meet.js</h2>
                    </div>;
          }
      });


var Hello = React.createClass({displayName: 'Hello',
          render: function() {
              return React.createElement("div", null, 
                            React.createElement("h1", null, "Hello"), 
                            React.createElement("h2", null, "meet.js")
                    );
          }
      });

JSX

  • JS and XML together
  • jsx (react-tools), webpack, browserify, grunt, gulp... or jsx-transformer + <script type="text/jsx">
  • jsx --watch <source_dir> <dest_dir>
  • js fiddle: http://jsfiddle.net/vjeux/kb3gN/

Virtual DOM

  • virtual DOM diff implementation for ultra-high performance
  • minimal set of DOM mutations 
  • render and test on the server - no browser needed
  • can re-render in 16ms

Events

var Hello = React.createClass({

        handler: function(event) {
            // handle event
        },

        render: function() {
              return <button onClick={this.handler}>Press me</button>;
          }
      });

React Developer Tools for Chrome

Few helpful things

Few notes

  • It's very easy to control and understand what is happening in React apps
  • Only most fundamental concepts were presented, React has more to offer
  • React is very easy to learn
  • People that have chosen React are very happy with their choice :)

Thank you :)

meet.js: Introduction to React

By Jacek Rzeszutek

meet.js: Introduction to React

  • 1,123