React
Understanding "state" in React Components
  •  

Creating a component with state

PRO
Outline

Creating a component with state

Let's continue our analogy with water by creating a <Water /> component. When initialized, this component will take the current temperature and render will output if it’s a solid, liquid or gas. Thus, the state of our <Water /> component will look like this:

{
    currentTemp: 60
}

We now have a Javascript object that we can use for our state, but how do we actually set it as our component’s state? When a React component initializes, you can set an initial state by defining a method called getInitialState that returns your desired state object:

getInitialState: function() {
    return {
        currentTemp: 60
    };
}

`

Perfect! The only thing remaining is to have the component tell us whether it’s a solid, liquid or gas. We can do this by accessing our currentTemp from our component’s state in the render method and compare it with boiling & freezing temperatures:

render: function() {
    // empty variable that will hold either "Liquid", "Solid", or "Gas"
    var stateOfMatter;

    // If temp is on/below freezing, it's a solid
    if (this.state.currentTemp <= 32) {
        stateOfMatter = 'Solid';

    // if temp is on/above boiling, it's a gas
    } else if (this.state.currentTemp >= 212) {
        stateOfMatter = 'Gas';

    // otherwise it's just a liquid
    } else {
        stateOfMatter = 'Liquid';
    }

    return (
        <div>
            <p>At { this.state.currentTemp }°F, water is considered to be a "{ stateOfMatter }" state of matter.</p>
        </div>
    );

}

Our component is now returning "At 60°F, water is considered to be a ‘Liquid' state of matter”; you can view the working code here!

Check this out — If you change the current temperature in getInitialState to 10, then click “Run” at the top of the page, the component should now say that it’s a “Solid” state of matter. Pretty cool, right?!

Now that you have a firm understanding of how state works in React, we can now start building truly interactive components. The next post will cover how to dynamically update state without refreshing the page by utilizing React’s setState method.