Hi,
Ive been trying to change divs colors separately everytime one of them is clicked, but something is not working. Im trying to handle keydown events and click events so I tried to create a method that assigns backgroundColor attribute for each single buttons div , to the col property in this.state.List in Buttons, so everytime the button is clicked, state only changes for the col attribute that the buttons is linked to . Something is not working and would really appreciate some feedback. How could I assign each Buttons component a separate color attribute in state?
Thanks
codepen: https://codepen.io/tonytony92/pen/QWbQyxW?editors=1111
here is my code so far:
class Buttons extends React.Component{
constructor(props){
super(props)
this.state={
List:[{
key:"Q",
col:"blue",
},{key:"W",
col:"blue"}]
}
this.handleEvent=this.handleEvent.bind(this)
this.assignColor=this.assignColor.bind(this)
}
handleEvent(evnt){
let clickId=evnt.target.id
let keyDownId=String.fromCharCode(evnt.keyCode)
console.log(clickId)
}
assignColor(event){
let clickId=event.target.id
let newState=Object.assign({},this.state)
if(clickId){
for(let i=0;i<this.state.List.length;i++){
if(this.state.List[i].key===clickId){
newState[i].col="red"
this.setState({
newState
})
return this.state.List[i].col
}
}
}
else{
return "blue"
}
}
render(){
document.addEventListener("click",this.handleEvent)
return(
<div>
<div style={{width:'100px', height:"100px", backgroundColor:this.assignColor}} id={this.props.id}><h3>{this.props.id} </h3></div>
</div>
)
}
}
class MyApp extends React.Component{
constructor(props){
super(props)
}
render(){
return(
<div>
<div style={{width:'400px',height:'400px', display:'flex',flexDirection:'row',backgroundColor:'green'}}>
<Buttons id="Q" color="blue"/>
<Buttons id="W" color="blue"/>
</div>
</div>
)
}
}
ReactDOM.render(<MyApp />, document.getElementById('root'))