Search code examples
javascriptreactjsinline-styles

Why doesn't react update the style in the setState?


Why doesn't react update the style in the setState? The color of the text does not update to green with the setState function, it remains blue.

class Practice extends Component {

    state = {
        count: 0,
        color: "blue"
    }

    style = {
        color: this.state.color
    }



    handleIncrement = () => {
        this.setState({ count: this.state.count});
        this.setState({ color: "green"});
    }

    render() {
        return(
            <div>
                <h1 style={this.style}>
                    The color in this state is {this.state.color}. 
                    The number in count is {this.state.count}.
                    <button
                    onClick={this.handleIncrement}
                    >
                    Increment 
                    </button>
                </h1>
            </div>
        );
    }

    }

Solution

  • While other answers explain well why your code is not working in terms of React state, there is one thing I noticed that might be another point of confusion.

    When you're assigning a value to your style property like this:

    style = {
        color: this.state.color
    }
    

    you might be thinking that you're assigning style.color a "reference" to the string that this.state.color points to. What actually happens is that you're assigning the value "blue", because the string is a primitive type in JS. So after you've done that, your style object is really just

    {
        color: "blue"
    }
    

    So even if you somehow change the value of this.state.color, this fundamentally wouldn't result in updating the value of this.style.color.