Should I Use ReactJS?

Should I Use ReactJS?

Short answer is Yes.

Long answer is unfortunately, Yes, for most things.

Here’s why you should use ReactJS:
- Works great for teams, strongly enforcing UI and workflow patterns.
- UI code is readable and maintainable.
- Componentized UI is the future of web development, and you need to start doing it now.

Here’s why you should think twice before you switch:
- ReactJS will slow you down tremendously at the start. Understanding how props, state, and component communication works is not straightforward, and the docs are a maze of information. This will be countered, in theory, by a grand speed up when your whole team is on board.
- ReactJS does not support any browser below IE8, and never will.
- If your application / website doesn’t have very much dynamic page updating, you will be implementing a lot of code for a very small benefit.
- You will reinvent a lot of wheels. ReactJS is young, and because there’s no canonical way to do events / component communication, you’ll have to build large component libraries from scratch. Does your application have dropdowns, resizable windows, or lightboxes? You’ll probably have to write those all from scratch.

So far go good, That’s it!!! See ya!!! :)

ReactJS Flux in Practice

ReactJS Flux in Practice

To build a ReactJS application with Flux I have deviced a little library called flux-react.

Actions
Actions are what links your components (and anything else that wants to change state) with your stores. You define them just by naming them. When calling an action the arguments will be deepCloned to avoid later mutation of complex objects passed to the store.

1
2
3
var Actions = flux.createActions([
  'addItem']
);

Stores
Stores are where you define your application state, update it and notify components about changes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var Store = flux.createStore({
  // We put the state directly on the store object
  lists: [],
  // Then we point to the actions we want to react to in this store
  actions: [
    Actions.addItem
  ],
  // The action maps directly to a method. So action addItem maps to the
  // method addItem()
  addItem: function (item) {
    this.lists.push(item);
    this.emit('list.add');
  },
  // The methods that components can use to get state information
  // from the store. The context of the methods is the store itself. 
  // The returned values are deepcloned, which means
  // that the state of the store is immutable
  exports: {
    getLists: function () {
      return this.lists;
    }
  }
});

Lets see how this is used in a component before going over the concept:

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
var ComponentList = React.createClass({
  getInitialState: function () {
    return {
      lists: Store.getLists()
    };
  },
  triggerAction: function () {
    Actions.addItem("Item added");
  },
  onChange: function () {
    this.setState({
      lists: Store.getLists()
    });
  },
  componentWillMount: function () {
    Store.on('lists.add', this.onChange);
  },
  componentWillUnmount: function () {
    Store.off('lists.add', this.onChange);
  },
  render: function () {
    return (
      <div>
        <button onClick={this.triggerAction}>Click</button>
        <br/><br/>
        {JSON.stringify(this.state.lists)}
      </div>
    );
  }
});

Okay. So what I noticed was that my actions always mapped directly to a method. If the action was called “addItem”, the method handling that action in my store was also called “addItem”. That is why actions in “flux-react” map directly to a method.

An other concept is the “exports”. You only want to expose a set of getter methods that your components can use. Three things happens with exports:
- The exports object is the object that is returned when creating a store.
- All methods in exports are bound to the store, letting you use “this” to point to the state in the store.
- Exported values are automatically deep cloned.

Now that last part needs a bit more explenation. The state, in your store should only be changed inside the store. ex. returning a list of todos to a component should not allow that component to do changes there that is reflected in the store. This is because of debugging. If lots of different components starts to change state directly in your store you will get into trouble. So instead the “flux-react” store makes sure that any value returned from exports is deep cloned, right out of the box. The same goes for complex objects passed as arguments to an action. We do not want them to be changed later outside of the store and by doing so change the state of the store.

How about performance? Well, the thing is that values you return from a store are not big, neither are values you pass as arguments. Yes, maybe you have a phonebook of 10.000 people in your store, but your interface will never show all 10.000 of them. You may grab the 50 first of them and the rest requires searching or pagination. In that case it is only the search result, or next page, that is deep cloned. Never all the 10.000 people.

Full codes:

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="http://fb.me/react-0.12.2.js"></script>
    <script type="text/javascript" src="http://fb.me/JSXTransformer-0.12.2.js"></script>
    <script src="flux-react.js"></script>
  </head>
<body>
  <script type="text/jsx">
    var Actions = flux.createActions([
      'addItem']
    );

    var Store = flux.createStore({
      lists: [],
      actions: [
        Actions.addItem
      ],
      addItem: function (item) {
        this.lists.push(item);
        this.emit('lists.add');
      },
      exports: {
        getLists: function () {
          return this.lists;
        }
      }
    });

    var ComponentList = React.createClass({
      getInitialState: function () {
        return {
          lists: Store.getLists()
        };
      },
      triggerAction: function () {
        Actions.addItem("Item added");
      },
      onChange: function () {
        this.setState({
          lists: Store.getLists()
        });
      },
      componentWillMount: function () {
        Store.on('lists.add', this.onChange);
      },
      componentWillUnmount: function () {
        Store.off('lists.add', this.onChange);
      },
      render: function () {
        return(
          <div>
            <button onClick={this.triggerAction}>Click</button>
            <br/><br/>
            {JSON.stringify(this.state.lists)}
          </div>
        );
      }
    });

    ReactDOM.renderComponent(<ComponentList />, document.body);
  </script>
</body>
</html>

You can download the source code here.

So far go good, That’s it!!! See ya!!! :)

What Is Flux?

What is Flux?

Flux is an architecture that Facebook uses internally when working with React. It is not a framework or a library. It is a new kind of architecture that complements React and the concept of Unidirectional Data Flow (Central to the Flux Pattern).

Facebook provide a Dispatcher javascript library. The dispatcher is a kind of global pub/sub handler that broadcasts payloads to registered callbacks.

Flux architecture will use this Dispatcher javascript library, along with NodeJS’s EventEmitter module in order to set up an event system that helps manage an applications state.

Flux have 4 layers:
- Actions - Helper methods that facilitate passing data to the Dispatcher.
- Dispatcher - Receives actions and broadcasts payloads to registered callbacks.
- Stores - Containers for application state & logic that have callbacks registered to the dispatcher.
- Controller Views - React Components that grab the state from Stores and pass it down via props to child components.

Structure and Data Flow
Data in a Flux application flows in a single direction:

What is Flux?

The dispatcher, stores and views are independent nodes with distinct inputs and outputs. The actions are simple objects containing the new data and an identifying type property.

The views may cause a new action to be propagated through the system in response to user interactions:

What is Flux?

All data flows through the dispatcher as a central hub. Actions are provided to the dispatcher in an action creator method, and most often originate from user interactions with the views. The dispatcher then invokes the callbacks that the stores have registered with it, dispatching actions to all stores. Within their registered callbacks, stores respond to whichever actions are relevant to the state they maintain. The stores then emit a change event to alert the controller-views that a change to the data layer has occurred. Controller-views listen for these events and retrieve data from the stores in an event handler. The controller-views call their own setState() method, causing a re-rendering of themselves and all of their descendants in the component tree.

What is Flux?

Summary
Flux is a pattern for unidirectional data flows Actions encapsulate events Dispatcher is a central hub that holds callbacks Stores hold app state Many implementations

So far after reading this article, I hope that if you didn’t get Facebook’s Flux Architecture before, that now you can say you do.

If you want to use the Flux architecture. but you don’t know how to use it and which library you should use, please stay turned for the next article. See you!!! :)

ReactJS Composable Components

ReactJS Composable Components

ReactJS is all about building reusable components. In fact, with React the only thing you do is build components. Since they’re so encapsulated, components make code reuse, testing, and separation of concerns easy. Let see the example below:

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript" src="http://fb.me/react-0.12.2.js"></script>
  <script type="text/javascript" src="http://fb.me/JSXTransformer-0.12.2.js"></script>
</head>
<body>
  <script type="text/jsx">
    var App = React.createClass({
      getInitialState: function() {
        return {
          red: 0
        }
      },
      update: function(e) {
        this.setState({
          red: this.refs.red.refs.inp.getDOMNode().value
        });
      },
      render: function() {
        return (
          <div>
            <NumInput
              ref="red"
              min={0}
              max={255}
              step={0.01}
              val={this.state.red}
              type="number"
              label="Red"
              update={this.update} />
          </div>
        );
      }
    });

    var NumInput = React.createClass({
      propTypes: {
        min: React.PropTypes.number,
        max: React.PropTypes.number,
        step: React.PropTypes.number,
        val: React.PropTypes.number,
        label: React.PropTypes.string,
        update:React.PropTypes.func.isRequired,
        type: React.PropTypes.oneOf(['number', 'range'])
      },
      getDefaultProps: function() {
        return {
          min: 0,
          max: 0,
          step: 1,
          val: 0,
          label: '',
          type: 'range'
        }
      },
      render: function() {
        var label = this.props.label !== '' ? <label>{this.props.label} {this.props.val}</label> : ''
        return (
            <div>
              <input
                ref="inp"
                type={this.props.type}
                min={this.props.min}
                max={this.props.max}
                step={this.props.step}
                defaultValue={this.props.val}
                onChange={this.props.update} />
                {label}
            </div>
        );
      }
    });

    React.render(<App txt="this is the txt prop" />, document.body);
  </script>
</body>
</html>

So far go good, That’s it!!! See ya!!! :)

ReactJS Mixins

ReactJS Mixins

Components are the best way to reuse code in React, but sometimes very different components may share some common functionality. These are sometimes called cross-cutting concerns. React provides mixins to solve this problem.

Example:

Let’s create a simple mixin that uses lifecycle methods for using in two components.

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript" src="http://fb.me/react-0.12.2.js"></script>
  <script type="text/javascript" src="http://fb.me/JSXTransformer-0.12.2.js"></script>
</head>
<body>
  <script type="text/jsx">
    var ReactMixin = {
      getInitialState: function() {
        return {count: 0}
      },
      componentWillMount: function() {
        console.log('will mount');
      },
      incrementCount: function() {
        this.setState({count: this.state.count+1});
      }
    }

    var App = React.createClass({
      render: function() {
        return(
          <div>
            <Button txt="this is the button" />
            <br/>
            <Label txt="this is the label" />
          </div>
        );
      }
    });

    var Button = React.createClass({
      mixins: [ReactMixin],
      render: function() {
        return <button onClick={this.incrementCount}>{this.props.txt} - {this.state.count}</button>
      }
    });

    var Label = React.createClass({
      mixins: [ReactMixin],
      componentWillMount: function() {
        setInterval(this.incrementCount, 1000);
      },
      render: function() {
        return <label>{this.props.txt} - {this.state.count}</label>
      }
    });

    ReactDOM.render(<App />, document.body);
  </script>
</body>
</html>

So far go good, That’s it!!! See ya!!! :)

ReactJS Component Lifecycle Unmounting

ReactJS Component Lifecycle Unmounting

ReactJS mounting have 1 methods:
- componentWillUnmount(): is invoked immediately before a component is unmounted and destroyed. Cleanup should go here.

Example:

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript" src="http://fb.me/react-0.12.2.js"></script>
  <script type="text/javascript" src="http://fb.me/JSXTransformer-0.12.2.js"></script>
</head>
<body>
  <script type="text/jsx">
    var Button = React.createClass({
      getInitialState: function() {
        return {
          val: 0
        }
      },
      handleUpdate: function() {
        this.setState({val: this.state.val + 1}
        );
      },
      componentWillMount: function() {
        console.log('mounting');
      },
      render: function() {
        console.log('rendering');
        return (
          <div>
            <button onClick={this.handleUpdate}>{this.state.val}</button>
          </div>
        );
      },
      componentDidMount: function() {
        console.log('mounted');
      },
      componentWillUnmount: function() {
        console.log('bye!');
      }
    });

    var App = React.createClass({
      handleMount: function() {
        React.render(<Button />, document.getElementById('app'));
      },
      handleUnmount: function() {
        React.unmountComponentAtNode(document.getElementById('app'));
      },
      render: function() {
        return(
          <div>
            <button onClick={this.handleMount}>Mount</button>
            <button onClick={this.handleUnmount}>Unmount</button>
            <div id="app"></div>
          </div>
        );
      }
    });

    React.render(<App />, document.body);
  </script>
</body>
</html>

In Button component getInitialState() method initial val: 0 by default.

When you click on Mount button, componentWillMount() method is invoked immediately before mounting occurs, and render() method render button into body DOM, and then componentDidMount() method is invoked immediately after mounting occurs.

When you click on Unmount button, componentWillUnmount() is invoked immediately before a component is unmounted and destroyed.

So far go good, That’s it!!! See ya!!! :)

ReactJS Component Lifecycle Updating

ReactJS Component Lifecycle Updating

ReactJS mounting have 4 methods:
- componentWillReceiveProps(object nextProps): is invoked when a mounted component receives new props. This method should be used to compare this.props and nextProps to perform state transitions using this.setState().
- shouldComponentUpdate(object nextProps, object nextState): boolean: is invoked when a component decides whether any changes warrant an update to the DOM. Implement this as an optimization to compare this.props with nextProps and this.state with nextState and return false if React should skip updating.
- componentWillUpdate(object nextProps, object nextState): is invoked immediately before updating occurs. You cannot call this.setState() here.
- componentDidUpdate(object prevProps, object prevState): is invoked immediately after updating occurs.

Example:

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
35
36
37
38
39
40
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript" src="http://fb.me/react-0.12.2.js"></script>
  <script type="text/javascript" src="http://fb.me/JSXTransformer-0.12.2.js"></script>
</head>
<body>
  <script type="text/jsx">
    var Button = React.createClass({
      getInitialState: function() {
        return {increasing: false}
      },
      handleUpdate: function() {
        this.setProps({val: this.props.val+1});
      },
      componentWillReceiveProps: function(nextProps) {
        this.setState({increasing: nextProps.val > this.props.val});
      },
      shouldComponentUpdate: function(nextProps, nextState) {
        return nextProps.val % 5 === 0;
      },
      render: function() {
        console.log(this.state.increasing);
        return(
          <div>
            <button onClick={this.handleUpdate}>{this.props.val}</button>
          </div>
        );
      },
      componentDidUpdate: function(prevProps, prevState) {
        console.log('prevProps', prevProps);
      }
    });

    ReactDOM.render(<Button val={0} />, document.body);
  </script>
</body>
</html>

So far go good, That’s it!!! See ya!!! :)

ReactJS Component Lifecycle Mounting

ReactJS Component Lifecycle Mounting

ReactJS mounting have 3 methods:
- getInitialState(): object is invoked before a component is mounted. Stateful components should implement this and return the initial state data.
- componentWillMount(): is invoked immediately before mounting occurs.
- componentDidMount(): is invoked immediately after mounting occurs. Initialization that requires DOM nodes should go here.

Example:

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript" src="http://fb.me/react-0.12.2.js"></script>
  <script type="text/javascript" src="http://fb.me/JSXTransformer-0.12.2.js"></script>
</head>
<body>
  <script type="text/jsx">
    var Button = React.createClass({
      getInitialState: function() {
        return {
          val: 0
        }
      },
      handleUpdate: function() {
        this.setState({val: this.state.val + 1}
        );
      },
      componentWillMount: function() {
        console.log('mounting');
      },
      render: function() {
        console.log('rendering');
        return (
          <div>
            <button onClick={this.handleUpdate}>{this.state.val}</button>
          </div>
        );
      },
      componentDidMount: function() {
        console.log('mounted');
      }
    });

    var App = React.createClass({
      handleMount: function() {
        React.render(<Button />, document.getElementById('app'));
      },
      render: function() {
        return(
          <div>
            <button onClick={this.handleMount}>Mount</button>
            <button onClick={this.handleUnmount}>Unmount</button>
            <div id="app"></div>
          </div>
        );
      }
    });

    ReactDOM.render(<App />, document.body);
  </script>
</body>
</html>

In Button component getInitialState() method initial val: 0 by default.

When you click on Mount button, componentWillMount() method is invoked immediately before mounting occurs, and render() method render button into body DOM, and then componentDidMount() method is invoked immediately after mounting occurs.

So far go good, That’s it!!! See ya!!! :)

ReactJS Component Lifecycle

ReactJS Component Lifecycle

ReactJS components have three main parts of their lifecycle:
- Mounting: A component is being inserted into the DOM.
- Updating: A component is being re-rendered to determine if the DOM should be updated.
- Unmounting: A component is being removed from the DOM.

ReactJS provides lifecycle methods that you can specify to hook into this process. We provide will methods, which are called right before something happens, and did methods which are called right after something happens.

So far go good, That’s it!!! See ya!!! :)

ReactJS Accessing Child Properties

ReactJS Accessing Child Properties

When you are building your React components, you’ll probably want to access child properties of the markup.

Parent can read its children by accessing the special this.props.children

Example:

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
35
36
37
38
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <script type="text/javascript" src="http://fb.me/react-0.12.2.js"></script>
  <script type="text/javascript" src="http://fb.me/JSXTransformer-0.12.2.js"></script>
</head>
<body>
  <script type="text/jsx">
    var App = React.createClass({
      render: function() {
        return (
          <Button>React <Heart /></Button>
        );
      }
    });

    var Button = React.createClass({
      render: function() {
        return(
          <button>{this.props.children}</button>
        );
      }
    });

    var Heart = React.createClass({
      render: function() {
        return (
          <span>Heart</span>
        );
      }
    });

    ReactDOM.render(<App />, document.body);
  </script>
</body>
</html>

App has two children Button and Heart, all thoes children come thought from {this.props.children}.

So far go good, That’s it!!! See ya!!! :)