ReactJS State

ReactJS State

What is State?

The state object is internal to a component. It holds data which can change over time. So far, we’ve used ReactJS as a static rendering engine. Now, we’re going to add state to make React components more dynamic.

The key difference between props and state is that state is internal and controlled by the component itself while props are external and controlled by whatever renders the component. Let’s see it in practice:

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>
  <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 Profile = React.createClass({
      getInitialState: function() {
        return {
          name: 'Bunlong'
        };
      },
      onNameInput: function(e) {
        this.setState({name: e.target.value});
      },
      render: function() {
        return (
          <div>
            <input type="text" onChange={this.onNameInput} />
            <h1>{this.state.name}</h1>
          </div>
        );
      }
    });

    React.render(<Profile txt="Bunlong VAN" />, document.body);
  </script>
</body>
</html>

State API

Getinitial State
Implement the function getInitialState which returns the initial state of the component. This is an object map of keys to values.

1
2
3
4
5
getInitialState: function() {
  return {
    name: "Bunlong"
  };
}

this.state
To access a component’s state use this.state just like how we use this.props.

this.setState
To update a component’s state, call this.setState with an object map of keys to updated values. Keys that are not provided are not affected.

1
2
3
this.setState({
  name: "Sokleap"
})

When a component’s state changes, render is called with the new state and the UI is updated to the new output. This is the heart of React.

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
<!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 Counter = React.createClass({
      getInitialState: function() {
        return {count: 0};
      },
      render: function() {
        return (
          <div>
            <h1>{this.state.count}</h1>
            <button type="button" onClick={this.increase}>Increase</button>
          </div>
        );
      },
      increase: function() {
        this.setState({count: this.state.count + 1});
      }
    });
    React.render(<Counter />, document.body);
  </script>
</body>
</html>

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