Reputation: 717
I have a stateful component that changes div background color after clicking on it. I keep a boolean flag in state, and when it changes, the component recalculating its color and rerendering itself.
How can I get rid of this boolean flag, I want to keep the color itself in state, and when the state with color changes, the component will rerender itself.
class App extends React.Component {
constructor(props) {
super(props);
this.state = { flag: true };
}
changeColor(){this.setState({flag: !this.state.flag})};
render(){
var bgColor = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
return ( <div style={{backgroundColor: bgColor}} onClick={this.changeColor.bind(this)}>wonderful</div> );
}
}
ReactDOM.render(<App />, document.getElementById('root'));
Upvotes: 0
Views: 4125
Reputation: 28685
Move this into changeColor
function
var bgColor = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
then store bgColor
inside state within same changeColor
function, e.g.
this.setState({ color: bgColor });
e.g.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {color: null};
}
changeColor(){
this.setState({
color: 'rgb(' + (Math.floor(Math.random() * 256)) + ',' +
(Math.floor(Math.random() * 256)) + ',' +
(Math.floor(Math.random() * 256)) + ')' })
};
}
render(){
return (
<div style={{backgroundColor: this.state.color}}
onClick={this.changeColor.bind(this)}
>
wonderful
</div>
);
}
Upvotes: 1
Reputation: 96
Make color a state variable, calculate the initial color using the color function on componentDidMount
, and then recalculate on click.
class App extends React.Component {
constructor(props) {
super(props)
this.setColor = this.setColor.bind(this)
this.state = {
color: null
}
}
componentDidMount () {
this.setColor()
}
setColor () {
let newColor = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')'
this.setState({color: newColor})
}
render () {
return (
<div style={{backgroundColor: this.state.color}} onClick={this.setColor}>
wonderful
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root' />
Upvotes: 1