Getting Started with Facebook’s React and Flux

reactjs flux
ReactJS Homepage

React and Flux are two of the most promising technologies of the present days, both are constantly showing up on trending technologies lists, quickly gaining market and becoming popular among developers. The first one defines itself as an open source javascript library for building user interfaces, it is an excellent tool for developers to create highly dynamic UI components, as the second is a brand new application architecture for client-side web apps designed to work together with React by using unidirectional data flow.

Let’s start by talking a little bit more about React with an example, and later on I’ll give more details about Flux and apply it to the first example.

Creating our first Application with React

The example bellow is a classic Hello World example using react:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
   <head>
	   <title>React Flux</title>
   	   <script src="https://fb.me/react-0.13.3.js"></script>
  	   <script src="https://fb.me/JSXTransformer-0.13.3.js"></script>
	   <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
   </head>
   <body>
	   <div id="component"></div>
 
 	   <script type="text/jsx">
		   var HelloWorld = React.createClass({
		     render: function() {
		       return <div>Hello World!!</div>;
		     }
		   });
 
		   React.render(<HelloWorld />, document.getElementById('component'));
 
	   </script>
   </body>
</html>

If you carefully analyze the code, the first different thing you should notice is the new script type text/jsx, which is basically Javascript with some HTML elements.

You can also see that I had to add three scripts to my page, the first and the second are the React and JSX scripts respectively, and the third one is jQuery, I’ll explain in a moment why we need it.

Now let’s analyze the code and see how it works, take a look at the declaration of HelloWorld var, this is the variable that will actually hold our new component. In React we always have to create the specification of our components through the function React.createClass, it receives an object as a parameter containing a render function, this function will process and return the component’s HTML code the way it’ll be displayed on the browser, in this example I’m just returning a div with a text within it, nothing dynamic for now.

After implementing our component we need just one more line of code to make it appear on the page, to show it we have to call React.render (line 19 of the example), this function receives two parameters, the first one is the component that will be displayed and the second one is where we want to display it, this is where JQuery will come into action, note that right after the body declaration we have a div with the id=component, I’m using JQuery’s getElementById to get this div and render my HelloWorld component on its place. Now if you run this application you should see ‘Hello World!!’ on your page.

Using Flux Architecture

flux architecture
Flux Homepage

As I said before Flux is a new architecture used by Facebook that complements React components by using unidirectional data flow, it is divided in four parts: the dispatcher, stores, views and controller-views. Every action, no matter where it comes from, is received by the dispatcher which will be responsible for changing the state of the appropriate store, after the state is modified it will notify the controller-view that will retrieve the new data and update all its child views.

Here is as brief explanation for each one of the components:

Dispacher – Is the central component that manages the data flow within the application, it distribute the actions to the appropriate stores.
Store – Components that contains the logic and state of the application.
View – The components that represent the user interface.
Controller-view – The type o view the listens to events coming from the stores.

It may be hard to understand at first but once you see an example it will get easier. To illustrate how this architecture works I’m going to use the same preview example but slightly modified just enough to demonstrate how Flux works, so instead of just showing ‘Hello World!!’ on the page we’re going to render a button that will trigger an action and show the hello world message, the difference is that now we have an action involved.

First we’re going to move our react code to another file that, it’ll be called HelloWorld.jsx, it should look like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
var React = require('react');
var HelloWorldAction = require('../Actions/HelloWorldAction.js');
 
var HelloWorld = React.createClass({
	showMessage:function(){
		HelloWorldAction.showMessage('Hello World!!');
	},
	render: function() {
		return <a onClick={this.showMessage}>Click Here</a>;
	}
});
 
module.exports = HelloWorld;

I’ve already made the changes, now I’m rendering a link that when clicked will trigger the showMessage function and pass our message to HelloWorldAction, which will be responsible to delivery it to the dispatcher, here is the HelloWorldAction code:

1
2
3
4
5
6
7
8
9
10
11
12
var Dispatcher = require('../Dispatcher/AppDispatcher.js');
 
var HelloWorldAction = {
	showMessage:function(message){
		Dispatcher.handleViewAction({
			actionType:'SHOW_MESSAGE',
			message:message
		});
	}
}
 
module.exports = HelloWorldAction;

Here I’m just wrapping my message that in this case will be my payload, and I’m also assigning an actionType to it, then I’m passing this action to the dispatcher:

1
2
3
4
5
6
7
8
9
10
11
12
13
var Dispatcher = require('flux').Dispatcher;
var assign = require('object-assign');
 
var AppDispatcher = assign(new Dispatcher(),{
	handleViewAction:function(action){
		this.dispatch({
			source:'VIEW_ACTION',
			action:action
		});
	}
});
 
module.exports = AppDispatcher;

This is the dispatcher code, here we have the implementation of the handleViewAction function that is receiving the payload from the HelloWorldAction, the purpose of this is to broadcast it to the stores, then the appropriate store can perform the action.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var Dispatcher = require('../Dispatcher/AppDispatcher.js');
var EventEmitter = require('events').EventEmitter;
var assign = require('object-assign');
 
var AppStore = assign({},EventEmitter.prototype,{
	emitChange:function(){
		this.emit('change');
	}
});
 
AppDispatcher.register(function(payload){
	alert(payload);
});
 
module.exports = AppStore;

Lastly we have our store, here I’m implementing and registering in the dispatcher the method that will actually show the message.

That’s it, now before you run it, since we used jsx code, you have to use browserify and reactify to compile it.

I know I didn’t give too much details on this tutorial, this application is so simple that it’s kind of weird to write that much code just to show a hello world message, I’m looking forward to write another post with a more complex application, this way we can explore react and flux a little further.