Reputation: 35
I have two components. Parent:
export default class GameBoard extends React.Component{
constructor(props){
super(props);
this.state={
boardPattern:[
' ',' ',' ',
' ',' ',' ',
' ',' ',' '
],
turn: "",
winner: null
}
}
handleClick(i){
console.log(i);
this.state.board[i]=this.state.turn
this.setState({
board:this.state.board,
turn: this.state.turn==='./images/x.ico'?'./images/y.ico':'./images/x.ico'
})
}
render() {
return (
<div>
{this.state.board.map(function(value, i){
return <Square key={i} turn={this.state.turn} onChange={()=>this.handleClick(i)}/>
}.bind(this))}
</div>
)
}
}
Child:
export default class Square extends React.Component{
handleClick = e => {
if ( typeof this.props.onTurnChange === 'function'){
this.props.onChange();
}
};
render(){
return <div className='Square' onClick={this.handleTurnChange}>
<img src={this.props.turn}></img>
</div>
}
}
I have an issue with handleClick function. Now when I click on each Square the state 'turn' (adding source image) is changed in every square. How can I make appear image only in Square that I have clicked?
Upvotes: 0
Views: 172
Reputation: 694
Well, I think the issue is that you can't do this.state.board[i]=this.state.turn
You cannot set a state value without using setState.
Try making a copy of the board, update it and set the state with the new value
Something like this
const updatedBoard = this.state.board.slice();
updatedBoard[i] = this.state.turn;
this.setState({board: updatedBoard});
In your example, I don't see where the board is initialized? I only see the pattern of the board in the state which shouldn't be there if it won't change.
Hope it helps you!
Upvotes: 1