Posts on this Category



How to load a JSON file in Reactjs

It’s really easy to load data from a JSON file in React. In this post I’m going to show you how you can do that. First, of course, we need a JSON file, you probably already have yours, but I’m using this movies list for this example:

data.json

[{"id": 1,"title": "Child Bride"}, 
{"id": 2, "title": "Last Time I Committed Suicide, The"}, 
{"id": 3, "title": "Jerry Seinfeld: 'I'm Telling You for the Last Time'"}, 
{"id": 4, "title": "Youth Without Youth"}, 
{"id": 5, "title": "Happy Here and Now"}, 
{"id": 6, "title": "Wedding in Blood (Noces rouges, Les)"}, 
{"id": 7, "title": "Vampire in Venice (Nosferatu a Venezia) (Nosferatu in Venice)"}, 
{"id": 8, "title": "Monty Python's The Meaning of Life"}, 
{"id": 9, "title": "Awakening, The"}, 
{"id": 10, "title": "Trip, The"}]

Now we have to place this file somewhere inside our project folder, it doesn’t necessarily need to be on the project, but it must be somewhere accessible via Http.

Once you have the path to your file you can load it this way:

import React, { Component } from 'react';
import data from './data.json';
 
class App extends Component {
  render() {
    return (
        <ul>
        {
          data.map(function(movie){
            return <li>{movie.id} - {movie.title}</li>;
          })
        }
        </ul>
    );
  }
}
 
export default App;

Note that all I had to do was to import the file in line 2, then the data was already ready for me to use on the data variable. Lastly, to show you how to use this variable I’ve made this component iterate over the dataset and display it on a list.

Easy right! If you have any doubts please let me know in the comments.

Tutorial: Sorting and Filtering a ReactJS Datatable

ReactJS Datatable with Sort and Filter
ReactJS Datatable with Sort and Filter

A few months ago I’ve made this post about how to create a reactjs datatable using the FixedDataTable module, I didn’t cover much, I just gave a simple example explaining how to populate the table with JSON data. Today we’re going a little further, continuing from where I stopped I’m going to show you how to sort and filter the data on this datatable.

Before we begin I’ll reorganize the code a little bit, let’s put all our datatable related code in a different file, I’ll name it myTable.js, its content should look like this:

import React from 'react';
import {Table, Column, Cell} from 'fixed-data-table';
 
class MyTable extends React.Component {
 
  constructor(props) {
    super(props);
    this.state = {
      rows : [{"id":1,"first_name":"William","last_name":"Elliott","email":"welliott0@wisc.edu",
             "country":"Argentina","ip_address":"247.180.226.89"},
              {"id":2,"first_name":"Carl","last_name":"Ross","email":"cross1@mlb.com",
             "country":"South Africa","ip_address":"27.146.70.36"},
              {"id":3,"first_name":"Jeremy","last_name":"Scott","email":"jscott2@cbsnews.com",
             "country":"Colombia","ip_address":"103.52.74.225"},
             // more data
    };
  }
 
  render() {
      return <Table
        height={40+((this.state.rows.length+1) * 30)}
        width={1150}
        rowsCount={this.state.rows.length}
        rowHeight={30}
        headerHeight={30}
        rowGetter={function(rowIndex) {return this.state.rows[rowIndex]; }.bind(this)}>
        <Column dataKey="id" width={50} label="Id" />
        <Column dataKey="first_name" width={200} label="First Name" />
        <Column  dataKey="last_name" width={200} label="Last Name" />
        <Column  dataKey="email" width={400} label="e-mail" />
        <Column  dataKey="country" width={300} label="Country" />
      </Table>;
  }
}
 
module.exports = MyTable;

I’m just making it because it’s a good practice, in this example it won’t make much difference, but in an application with multiple components it would get really messy if you put everything on the main.js.

After isolating the datatable component our main.js is much cleaner:

import MyTable from './myTable';
import React from 'react';
import ReactDOM from 'react-dom';
 
ReactDOM.render(<MyTable/>,document.getElementById('example'));

If you run the project now you should see the exact same result as before, now let’s start adding some features to this table.

Filtering the data

We have to make a few changes in the constructor in order to add the filter functionality:

constructor(props) {
  super(props);
  this.rows = //json data
  this.state = {
    filteredDataList: this.rows
  };
}

As you can see I took the rows variable out of the state and replaced it with filteredDataList, now you must think of rows as our data source, like a database table or a web service it shouldn’t be part of our state, what should be is the data we are actually displaying on the table, which will be the filteredDataList. Initially it will have the exact same data as the rows variable, but as the user starts filtering, its value will change.

After this, the attributes height, rowsCount and rowGetter of our table are still referencing the rows variable, as the table won’t interact directly with this variable anymore, they should be changed to reference the filteredDataList.

Now let’s add to our class the methods responsible for the filtering:

_renderHeader(label, cellDataKey) {
  return <div>
        <span>{label}</span>
          <div>
            <br />
            <input style={{width:90+'%'}} onChange={this._onFilterChange.bind(this, cellDataKey)}/>
          </div>
      </div>;
}
 
_onFilterChange(cellDataKey, event) {
  if (!event.target.value) {
    this.setState({
      filteredDataList: this.rows,
    });
  }
  var filterBy = event.target.value.toString().toLowerCase();
  var size = this.rows.length;
  var filteredList = [];
  for (var index = 0; index < size; index++) {
    var v = this.rows[index][cellDataKey];
    if (v.toString().toLowerCase().indexOf(filterBy) !== -1) {
      filteredList.push(this.rows[index]);
    }
  }
  this.setState({
    filteredDataList: filteredList,
  });
}

The _renderHeader() function tells the Column what should be rendered on it’s header, in this case it’s just adding an input so the user can type and filter the data, on its onChange event I’m calling the function _onFilterChange which will actually do the filtering and update the filteredDataList value.

Lastly we have to call the _renderHeader function on our columns like this:

<Column dataKey="id" width={50} label="id"  
     headerRenderer={this._renderHeader.bind(this)}/>

Note that I’ve used bind() to call the function _renderHeader(), it’s really important that you do exactly like that, otherwise you will come across the problem described here.

Now you can run your project, if you did everything right you should see an input bellow the label on the header, if you type something in there you’ll see that the filter is already working.

Making the Columns Sortable

In order to use the sort feature we have to add two more attributes to the state: sortBy and sortDir:

 
constructor(props) {
  super(props);
  this.rows = //json data
  this.state = {
    filteredDataList: this.rows,
    sortBy: 'id',
    sortDir: null
  };
}

The first is responsible for telling by which column our datatable is currently being sorted by, it’s being initialized with the column id, and the second is just for allowing us to control whether it’s ASC or DESC.

We also have to modify the _renderHeader() a little bit:

_renderHeader(label, cellDataKey) {
  return <div>
        <a onClick={this._sortRowsBy.bind(this, cellDataKey)}>{label}</a>
          <div>
            <br />
            <input style={{width:90+'%'}} onChange={this._onFilterChange.bind(this, cellDataKey)}/>
          </div>
      </div>;
}

I just replaced the span with a link where the user will click to sort the table, on the onClick event it calls the following function:

_sortRowsBy(cellDataKey) {
  var sortDir = this.state.sortDir;
  var sortBy = cellDataKey;
  if (sortBy === this.state.sortBy) {
    sortDir = this.state.sortDir === 'ASC' ? 'DESC' : 'ASC';
  } else {
    sortDir = 'DESC';
  }
  var rows = this.state.filteredDataList.slice();
  rows.sort((a, b) => {
    var sortVal = 0;
    if (a[sortBy] > b[sortBy]) {
      sortVal = 1;
    }
    if (a[sortBy] < b[sortBy]) {
      sortVal = -1;
    }
 
    if (sortDir === 'DESC') {
      sortVal = sortVal * -1;
    }
    return sortVal;
  });
 
  this.setState({sortBy, sortDir, filteredDataList : rows});
}

This function is responsible for the sorting, if you take a look at the code you’ll see that in order to “decide” how the table should be sorted it uses and modifies the two new variables we added to the state, at the end it sets the state again with the modified values.

Now add this code to your render() function, right before returning your component:

var sortDirArrow = '';
if (this.state.sortDir !== null){
  sortDirArrow = this.state.sortDir === 'DESC' ? ' ↓' : ' ↑';
}

This code is just for controlling the arrow that will be displayed in front of the column label. Don’t forget to add the logic to your column label attribute as well, otherwise the arrow won’t be displayed.

<Column dataKey="id" width={50} 
  label={'id' + (this.state.sortBy === 'id' ? sortDirArrow : '')}
  headerRenderer={this._renderHeader.bind(this)}/>

Ok, now we are done with the sorting and filtering, if you run your project the result should be exactly the same as the gif at the beginning of this post.

That’s it! Hope you enjoyed the tutorial, just leave a comment if you have any doubts.

ReactJS Error: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.

This is a very common error for reactjs beginners, if you are facing this error it means your render method is modifying the state of your component, causing it to re-render, which then will modify it again and so on. You are dealing with an infinite loop here, if you take a look at your console (before your browser crashes) you’ll see something like this:

setState(...): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.
setState(…): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.

Before I explain how to solve it I’ll show you the most probable reason why it’s happening, let’s analyze the following component:

class ErrorSimulation extends React.Component {
 
  constructor(props) {
    super(props);
    this.state = {
      x : 1
    };
  }
 
  _changeValue(newValue){
    this.setState({newValue});
  }
 
  render() {
    return <a onClick={this._changeValue(2)}>Change Value</a>
  }
}

Note that the render() method is calling the function _changeValue(), if you take a look at this function you’ll see that it’s modifying the state. Nothing wrong, right? This should be OK, otherwise how would the component be able to modify it’s own state? Well, the problem here is the way we call the function, by doing it like I did in this example the function _changeValue() will actually be called and executed right away during the state transition, this will cause the problem. We can solve that by changing a little bit the way we call the function.

Instead of doing this:

<a onClick={this._changeValue(2)}>Change Value</a>

we call it like this:

<a onClick={this._changeValue.bind(2)}>Change Value</a>

By using bind() your function won’t be called during the state transition anymore, it will complete the process and leave the function to be called later, this will prevent the problem from happening.

ReactJS DataTable with Sort, Filter and Pagination Example (PART 1)

fixed-data-table home page
fixed-data-table home page

Today we’re going to learn how to create a simple datatable for react using the FixedDataTable module, since it uses Javascript ES6 code you must have at least some basic knowledge about it. To c ompile our ES6 code we’re going to use Babel and Webpack, since our js files will also contain JSX and React code, besides babel-preset-es2015 we are going to need babel-preset-react as well.

So let’s get started, create your project folder and run npm init to create the package.json file, after that we need to add all the dependencies, the following code has everything we need, just copy and paste it in there:

package.json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.3.17",
    "babel-loader": "^6.2.0",
    "babel-preset-es2015": "^6.3.13",
    "babel-preset-react": "^6.3.13",
    "babel-runtime": "^6.3.19",
    "webpack": "^1.12.9"
  },
  "dependencies": {
    "fixed-data-table": "^0.6.0",
    "react": "^0.14.3",
    "react-dom": "^0.14.3"
  }
}

As devDependencies(dependencies we need only for development) we have webpack and some babel modules, and as regular dependencies we’ll only need react and the fixed-data-table module. Now run npm install, it’ll download and install all the dependencies, it may take a while.

The next step is to configure the webpack module, to do that we need to create the webpack.config.js file and add the following code to it:

webpack.config.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
"use strict";
 
module.exports = {
  entry: './main.js',
  output: { path: __dirname, filename: 'bundle.js' },
 
  module: {
    loaders: [
      {
        test: /.js?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
};

In this file I’m just specifying the files webpack should transform (or transpile) and what loaders it should use to do it. As the entry file we have the main.js, and as the output (the transformed file) we have the bundle.js, both files were not created yet. We’re also saying to webpack that babel-loader will be our loader and that it should test and transform every js file in our project, except the ones inside the node_modules folder. Lastly we are defining es2015 and react as our presets.

OK, now we’re ready to write some code, first let’s create the main.js file with the following code:

main.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import React from 'react';
import ReactDOM from 'react-dom';
import {Table, Column, Cell} from 'fixed-data-table';
 
const rows = [{"id":1,"first_name":"William","last_name":"Elliott","email":"welliott0@wisc.edu",
"country":"Argentina","ip_address":"247.180.226.89"},
{"id":2,"first_name":"Carl","last_name":"Ross","email":"cross1@mlb.com",
"country":"South Africa","ip_address":"27.146.70.36"},
{"id":3,"first_name":"Jeremy","last_name":"Scott","email":"jscott2@cbsnews.com",
"country":"Colombia","ip_address":"103.52.74.225"},
 
// more data
];
 
ReactDOM.render(
    <Table
      height={rows.length * 30}
      width={1150}
      rowsCount={rows.length}
      rowHeight={30}
      headerHeight={30}
      rowGetter={function(rowIndex) {return rows[rowIndex]; }}>
 
      <Column dataKey="id" width={50} label="Id" />
      <Column dataKey="first_name" width={200} label="First Name" />
      <Column  dataKey="last_name" width={200} label="Last Name" />
      <Column  dataKey="email" width={400} label="e-mail" />
      <Column  dataKey="country" width={300} label="Country" />
 
    </Table>,
    document.getElementById('example')
);

This code can already gerenate a basic datatable, but without any features yet (sort, filter and pagination). As you can see I’ve used some JSON data to populate the datatable, but feel free to use your own data if you want. Now if you take a look at the code of our actual table component you’ll see that it’s really easy to understand, almost every attribute of the Table tag is responsible for controlling its dimensions, except the rowGetter, which is responsible for saying where each row should get its data. We should focus on the Column tags, which by far are also very simple, besides the attribute width, we have the dataKey and label, the first one is the name of the JSON field that will be displayed in this column, and the second is the text that will appear in the header.

Now let’s create our HTML:

index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>React DataTable</title>
    <link href="node_modules/fixed-data-table/dist/fixed-data-table.css" 
          rel="stylesheet">
  </head>
  <body style="font-family:arial;font-size:12px; background:#e1e1e1">
    <div id="example"></div>
    <script src="bundle.js"></script>
  </body>
</html>

This is just a regular html file, I just added the css from the fixed-data-table module and also the bundle.js, which is the compiled version of our main.js, it’s really important that you put the bundle.js at the end of the body, otherwise it won’t be able to render the datatable.

Now just run the command webpack to generate the bundle.js, if everything goes right you can now open your index.html file on your browser, this should be the result:

ReactJS datatable
ReactJS datatable

Perfect!! Now our datatable can already show the data in the browser, the next step is to start adding some features to this table, like pagination, sorting and filtering, but I’ll leave that to the PART 2 of this tutorial.

That’s it for today!! hope you enjoyed, till the next one!!

Compiling JSX ReactJS code with Browserify and Reactify

This will be a very basic tutorial for those who are just getting to know React, by now you should have noticed that React uses JSX code, which is basically Javascript with some HTML elements. The problem here is that the browser cannot understand JSX, if you have already tried it you probably saw something like this on your firebug:

SyntaxError: expected expression, got ‘<'

In order to make it possible for the browser to interpret it we have convert the JSX into regular Javascript code, to achieve that we need to use tools like Browserify and Reactify.

Browserify, is a tool that let’s you use the function require(‘module’) in the front-end exactly like you do in the back-end with Node.js, then it compiles everything and generates a single JS file which will be referenced on your page. Reactify is pretty much the same thing, but it supports JSX code, Browserify alone wouldn’t be able to compile it.

Let’s take a look at an example, the first thing you need to do is to install both browserify and reactify:

1
2
3
4
5
//INSTALLS BROWSERIFY
npm install browserify
 
//INSTALLS REACTIFY
npm install reactify

Now, you probably have in you project a JSX file like this one (in my case it’s on the ‘src’ folder):

app.jsx

1
2
3
4
5
6
7
8
9
var ReactDOM = require('react-dom');
var React = require('react');
 
var HelloWorld = React.createClass({
 render: function() {
   return <div>Hello World!!</div>;
 }
});
ReactDOM.render(<HelloWorld />, document.getElementById('component'));

What you need to do now is to transform this into a JS file so the browser can read it, already with browserify and reactify installed just navigate to your project folder and type the following command:

1
browserify -t reactify src/app.jsx -o build/app.js

Perfect!! Now you have the app.js file in your ‘build’ folder, you can now use it in your HTML page like this:

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
   <head>
	   <title>React DataTable</title>
	   <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
   </head>
   <body>
	   <div id="component"></div>
	   <script src="build/app.js"></script>
   </body>
</html>

That’s it!! Hope I helped you with this tutorial, till the next one!!

React.js Tutorial: Consuming JavaEE RESTful Web Services

In this post I’m going to show how to consume Web Services with React.js, more specificalyJavaEE RESTful Web Services. I’ve already written a post showing how to create these web services with EJB 3, if you haven’t seen it yet just click on this link for more details, but if you’re already familiar with Java EE feel free to skip it and create your owm web service.

For this tutorial I’m going to use the following service (Which is almost the same as I created on the other post):

1
2
3
4
5
6
7
8
9
10
11
@Stateless
@Path("/test")
public class WebServiceTest {
 
    @GET
    @Produces("text/plain")
    public String test() {
        return "Web Service Test";
    }
 
}

This is as simple as it gets, just a method returning a string, simple as that! If you deploy the project you’ll be able to see the text “Web Service Test” on your browser by adding /test to the end of your URL:

Java EE REST Web Service Example
Java EE REST Web Service Example

Now let’s create the React.js project to consume this web service. Again, I already have a post about how to get started with React.js, click on the link to see it, though it doesn’t say anything about how to consume web services it can still be useful for those who are not familiar with react.

Since my goal here is to just show how to consume a web service, I’ll keep the react code very simple as well, just copy the following code into your index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!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 JavaEEWSTest = React.createClass({
                getInitialState: function () {
                    return {text: ''};
                },
                componentDidMount: function(){
                    $.ajax({
                        url: "http://localhost:8080/WebServiceEJB-war/test"
                    }).then(function(data) {
                        this.setState({text: data});
                    }).bind(this)
                },
                render: function() {
                    return <div>Response - {this.state.text}</div>;
                }
            });
 
            React.render(<JavaEEWSTest />, document.getElementById('component'));
 
        </script>
    </body>
</html>

As you can see I have 3 functions here: getInitialState, componentDidMount and render. They do exactly what their names sugest, the first one sets all the initial values, the second executes when the component is mounted, and the last one is responsible for rendering the component. The most important for us is the componentDidMount, that’s where the web service is called, and after it receives the response it will be assigned to the variable ‘text’.

We’re almost done, now if you execute it you will probably see the following error (you need firebug installed):

Cross-Origin Request Blocke
Cross-Origin Request Blocke

To see more details about this error click here, to solve it just add the following filter to your Java EE project:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
 
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
 
public class CORSFilter implements Filter {
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
            FilterChain filterChain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, HEAD, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Origin, Accept, x-auth-token, "
                + "Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
        filterChain.doFilter(servletRequest, servletResponse);
    }
 
    @Override
    public void destroy() {
 
    }
 
}

And in the web.xml:

1
2
3
4
5
6
7
8
<filter>
    <filter-name>cors</filter-name>
    <filter-class>yourPackage.CORSFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Perfect!! Now if you refresh the page this will be the result:

Simple React.js application getting data from Java EE REST Web Service
Simple React.js application getting data from Java EE REST Web Service

It’s really simple, but the string ‘Web Service Test’ is coming from our web service.

Hope this tutorial was helpful for you, till next time!

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.