Reputation: 113
Despite trying to avoid all the documented pitfalls which prevent React from re-rendering after state-change, I've still not been able to figure out my problem:
// Grid.js, render a grid of random-colored boxes
constructor(props){
super(props);
this.initialcolors = this.initialcolors.bind(this);
this.updatecolors = this.updatecolors.bind(this);
this.state = {colors: this.initialcolors()}
}
// ...
updatecolors(index){
let currentColors = [...this.state.colors];
let currentColor = currentColors[index];
let newColors = this.props.colors.filter(c => c !== currentColor)
let newColor = newColors[Math.floor(Math.random() * newColors.length)];
currentColors[index]=newColor;
this.setState(st => ({colors: currentColors}))
}
render(){
return(<div>
{this.state.colors.map( (color, index) =>
<Box key={index} position={index} color={color} updatefunc={this.updatecolors} className="Box.css"/>
)}
</div>)
}
// Box.js, the colored box, onClick triggers state-change by calling updatefunc from parent
constructor(props){
super(props);
this.state = {color: this.props.color};
this.changeColor = this.changeColor.bind(this);
}
changeColor(evt){
this.props.updatefunc(this.props.position);
}
render(){
return(
<div style={{backgroundColor: this.state.color,
height: 100,
width: 100,
padding: 0.5}}
onClick={this.changeColor}> </div>
)
}
}
The update-function is called from each box-component and triggers assignment of a new color on the box grid.
Trying to avoid the usual mistakes:
However, despite onClick successfully triggering the state change, there is no re-render taking place. What is the additional aspect that I am missing here?
Many thanks in advance!
Upvotes: 0
Views: 1325
Reputation: 2642
Box.js is using this.state.color
as the backgroundColor, which never changes because the constructor is only called once per box. You probably want to use this.props.color
which has the changed color from Grid.
class Box extends Component {
constructor () {
super();
this.changeColor = this.changeColor.bind(this);
}
changeColor (evt) {
this.props.updatefunc(this.props.position);
}
render () {
return (
<div
style={{
backgroundColor: this.props.color,
height: 100,
width: 100,
padding: 0.5
}}
onClick={this.changeColor}
/>
)
}
}
Upvotes: 1