React

Why?

  • Nice component structure
  • Faster at rendering than other SPA libraries (that we've used)
  • No need to do optimizations for lists etc
  • Works well with Browserify

What?

  • UI rendering library
  • Fast!
  • Compatible with IE8 and above
  • Built by Facebook

Not an MVC Framework

No two-way data binding

No event system/observables

Components

  • React.createClass({ ... })
  • render()
  • getInitialState()
  • this.state
  • this.props

JSX

  • No HTML
  • HTMLish in Javascript
  • Compilation step
  • Can be interpreted in browser when developing 
var MyCounter = React.createClass({
  render: function () {
    return (
      <button>I don't do anything... yet.</button>
    );
  }
});
var MyCounter = React.createClass({
  getInitialState: function () {
    return {
      count: 0
    };
  },
  onButtonClicked: function () {
    this.setState({
      count: this.state.count + 1
    });
  },
  render: function () {
    return (
      <button onClick={this.onButtonClicked}>
        Counter is {this.state.count}.
      </button>
    );
  }
});
var MyCounter = React.createClass({
  // ...
});

React.render(
  <MyCounter />,
  document.body
);
var Child = React.createClass({
  onDeleteClick: function () {
    this.props.onDelete();
  },
  render: function () {
    return (
      <button onClick={this.onDeleteClick}>
        Delete
      </button>
    );
  }
});
var Parent = React.createClass({
  onChildDelete: function (childData) {
    backend.delete(childData);
  },
  render: function () {
    var childData = {};
    return (
      <Child onDelete={this.onChildDelete.bind(this, childData)} />
    );
  }
});

Virtual DOM

  • render() returns a component
  • Synthetic events
  • Performs a diff to calculate actual DOM changes 

Works well with...

  • Backbone collections, models
  • Bacon.js, rx.js
  • Browserify
  • Good ol' callbacks

Server-side rendering

  • SEO
  • Fast page loads
  • (Javascript-disabled browsers)

Lab

React

By oskarwickstrom

React

  • 672