Reputation: 37
I'm trying to use setState on a click to update my element with a property passed from a parent element, but the state of my element won't update.
I've tried adding and removing "this" to a few spots and also having everything in the constructor function, but for whatever reason the state still doesn't change.
changeToBlack = (e)=>{
this.setState({
buttonClicked:'black'})
}
render(){
return (
<div>
<button onClick={this.changeToRed}>change To Red</button>
<button onClick={this.changeToBlack}>change To Black</button>
<div className="grid">
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze} className= 'cell'/>
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze}className= 'cell'/>
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze}className= 'cell'/>
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze}className= 'cell'/>
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze}className= 'cell'/>
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze}className= 'cell'/>
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze}className= 'cell'/>
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze}className= 'cell'/>
<Square button={this.state.buttonClicked} color={this.state.colorToChangeMaze}className= 'cell'/>
</div>
</div>
);}
}
class Square extends Component{
constructor(props) {
super(props);
this.state = {
color: 'orange',
colorToChange:null,
changeColor: false
};
}
switchColor =(e)=>{
this.setState({
changeColor:true,
colorToChange:this.props.button})
}
render(){
return(
<input onMouseOver = {this.switchColor} style={{'height':'74px','width':'74px','backgroundColor':this.state.changeColor?this.state.color:this.state.colorToChange,'margin':'0'}}>
</input>
)
}
I'm really unsure why the colorToChange stays at null and the changeColor stays at false. Any help would be appreciated.
Upvotes: 0
Views: 42
Reputation: 4662
I think you want to switch these variables round as at the moment it will set the background color to null
then once you hover over the input it will always set it to this.state.color
which is always orange.
You should change:
this.state.changeColor?this.state.color:this.state.colorToChange
To:
this.state.changeColor ? this.state.colorToChange : this.state.color
Upvotes: 1