O'Reilly logo

Mastering React by Ryan Vice, Adam Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

state

So far our components are static and don't allow for dynamic behavior, which isn't very interesting and we would need to be able to make our components dynamic for them to be useful. React components have the concept of state to allow for dynamic behavior. The following code shows how we can use state to create some simple dynamic behavior:

var HelloReact = React.createClass({
  getInitialState: function() {
      return {
          message: 'I am from default state'
      };
  },
  updateMessage: function(e) {
      this.setState({message: e.target.value});
  },
  render: function() {
    return (
      <div>
        <input type='text' onChange={this.updateMessage}/>
        <div>Hello React</div>
        <div>{this.state.message}</div>
      </div>
      );
  }
});

ReactDOM.render(
  <HelloReact />, 
  document.getElementById('view')) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required