Introduction to React and Flux

Created by Tahir J / @1codejs

What is React?

It's a JavaScript Library for building User Interfaces.

Created by Facebook

  • It only focuses on the view layer (It's the V in MVC)
  • It makes no assumptions about the rest of your front-end stack
  • Can be plugged into an existing MVC (MV*) framework like:
    • Angular
    • Ember
    • Backbone
  • It comes in 3 flavours
    • React JS (Web)
    • React Native (iOS)
    • React Native (Android)

But what is MVC?

Stands for Model, View, Controller.

Software architectural pattern for implementing user interfaces.

Model: Is where the application's data is stored. The model doesn't have knowledge about views or controllers.

View: What's presented to the user, and is how a user interacts with the application.

Controller: The glue between the model and view. Controllers update the view when the model changes, and update the model when the user manipulates the view.

Important: MVC architectures can vary significantly from this traditional definition.

Misconceptions (What React isn't)

  • Not a front-end MVC framework
  • Not a straight alternative to Angular, Ember or Backbone
  • Not a template library (like: Handlebars, Mustache, Hogan)

How should I structure a React app?

Flux (By Facebook)

An application architecture based on unidirectional data flow.

It's more of a pattern than a formal framework.

Data flow (React/Flux Application)

Actions (Not DOM events)

  • Think of Actions as Newspapers, reporting on something that happened in the world
  • Represent mutations in you application state
  • Action examples:
    • A tweet is retweeted
    • A user is followed in Beamly
    • A comment posted
    • An article is liked

Dispatcher

  • Used to broadcast payloads to registered callbacks (Stores)
  • A singleton, and operates as the central hub for data flow
  • Similar to pub-sub systems
  • Uses Node's Event Emitter
  • It's essentially a registry of callbacks
  • When new data is received, it uses these callbacks to propagate that data to all of the Stores

Stores (Model like... but not)

  • Contains your application state
  • The single source of truth
  • Each Store registers a callback with the Dispatcher
  • Read-only
  • Updated as a result of Actions
  • Self contained universe
  • Emits an event when internal state changes...

Views (React)

  • Types: Controller views, Parent views, Child views
  • Controller views listen and react to Store events
  • They can optionally update their state, re-render themselves and their children
  • Also, they can respond to user interaction, and fire Actions that will eventually mutate Stores...

Virtual DOM (HOW AND WHY)

An in-memory representation of the real DOM, that allows you to keep expensive writes to the DOM, to a minimum.

  • Incredibly fast
  • Re-rendering is very cheap
  • DOM manipulations are batched
  • Updates to the real DOM are localised only to the parts that changed
  • Events are normalised across browsers
  • Events are automatically delegated for you...

JSX

JavaScript XML syntax

React components contain the mark-up (JSX/HTML) necessary for rendering themselves.

  • Components can be written in pure JavaScript or what React calls JSX
  • Allows you to write a HTML 'like' syntax inside your JS files, which is compiled down to regular JavaScript

We've all been conditioned to separate our functionality from our views, but if you think about it, they are actually intrinsically linked.

Markup, and the code that generates it, are intimately connected.

Display logic is often very complex, and using a templating language to express it, can become cumbersome as the application grows...

React Components

A reusable UI element with a well defined interface.

Possible examples: Like buttons, Navigation bar, Beamly user feed, Feed item, Tweet, Drop-down menu, Image upload, Beamly search, Auto suggest input, Carrrrrrrousel.

  • Encourages reuse and abstraction
  • Similar to jQuery plugins...
  • Can be as simple as plain HTML
  • Or as complex as HTML, CSS, JS
  • Can contain child components
  • E.g. React Bootstrap...

How can I traverse the DOM / Virtual DOM

"React encourages the creation of small self-contained components. If you're attempting to traverse the DOM, outside of your component, you're probably doing something wrong!"

Using React

  • You can access HTML elements, within a component using ref attributes:
    
     <input type="text" ref="myTextInput" />
                                    
  • Use this.refs property to obtain references to things, similar to jQuery's $(el).find(); :
    
    var myTextInput = this.refs.myTextInput;
                                    
  • Actual DOM nodes are accessed using the React findDOMNode method:
    
    var domNode = React.findDOMNode(myTextInput);
                                    

Using jQuery

Once a component has been loaded into the DOM, it's possible to use jQuery if necessary:


componentDidMount() {
    var $ = require('jquery');
    var myTextInput = this.refs.myTextInput;
    var domNode = React.findDOMNode(myTextInput);
    var $input = $(domNode);

    $input.animate({
        opacity: 0.25,
        left: '+=50'
    }, 5000, function () {
        $(this).hide();
    });
}
                        

Or... use the component as the starting point via this:


componentDidMount() {
    var $ = require('jquery');
    var reactComponentNode = React.findDOMNode(this); // <--
    var $component = $(reactComponentNode);

    var $body = $component.closest('body'); // DON'T DO THIS!
    $body.css({ backgroundColor: '#000' });

    var $input = $component.find('input[ref="myTextInput"]');
    $input.fadeOut(2000);
}
                        

Browser compatibility

  • IE8 +
  • React is pretty good at abstracting browser differences...
  • Older browsers may need polyfils

Isomorphic JavaScript

(Server side rendering)

  • CommonJS on both client and server
  • Node (Fat server / Fat client)
  • More shared code (Increases code reuse)
  • Browserify (compile JSX, ES6 to ES5, create bundle.js)
  • Easily achievable using Node express
  • Server-side solutions available in backend languages like Ruby Rails, Scala, Java, PHP

Contrived example


// app.js
var React = require('react');
var SomeConponent = require('./someConponent');

var ReactApp = React.createClass({
    render() {
        return (<SomeConponent />);
    }
});

module.exports = ReactApp;
                        

// server.js
var React = require('react');
var express = require('express');
var appComponent = require('../public/js/components/app');
var ReactApp = React.createFactory(appComponent);
var app = express();

app.get('/some-conponent/:id', function(req, res) {
    var html = React.renderToString(
        ReactApp()
    );
    res.end(html);
});
                        

Who uses it? (May 2015)

Facebook states 130+ companies / apps

Instagram, Atlassian, BBC, Codecademy, Dropbox, Flipboard, Imgur, Khan Academy , Netflix, Reddit, The New York Times, Uber, WhatsApp, Wired, Yahoo, Zendesk, Atom Editor, Brackets Editor

How and where is it being used @ Beamly

  • Beamly Booster
  • who else?

Is React just a new bandwagon to jump on?

Maybe!

But Facebook use it, so you know it can scale

Try it for size with a Todo MVC app

Time will tell...

Final words

  • React is very simple (V in MVC)
  • Encourages an alternative way of thinking, even if it feels dirty at first
  • Isomorphic JavaScript
  • Encourages ES6 (Reactify, Browserify, Babel)
  • Combine with Flux for unidirectional data flow
  • For developers with opinions (Models, Controllers Routing etc.)

As experienced software engineers at Beamly, we don’t want to be tied down by a framework, we want to be empowered to make our own decisions about the components we use to build our applications.

QUESTIONS?

Thanks!

Tahir J

@1codejs