How to reflect the new state in render() after changing state in componentWillReceiveProps()

How to reflect the new state in render() after changing state in componentWillReceiveProps()
0

#1

`class Board extends React.Component {
constructor(props) {
super(props);
this.state = {
grid: props.grid
}
}
updateGrid(updatedGrid) {
this.setState = {
grid: updatedGrid
}
}
componentWillReceiveProps(newProps) {
this.updateGrid(newProps.grid)

}

toggleCellState(row,col) {
let board = [];
this.state.grid.map(function(arr,i) {
board[i] = arr.slice()
})
board[row][col] = !board[row][col];
this.setState({
grid: board
})
}

render() {
//console.log(this.state.grid)
var rows = []
this.state.grid.map((row,i) => {
rows.push()
})
return (

{rows}

)
}
}`

This is part of my code from Project Game of Life.Here I am receiving an updated grid from parent in componentWillreceiveProps() as a newProps,then from here I am calling updateGrid() to update my grid using this.setState(). Now I am expecting that in render() I should get updated grid but it’s not happening. Can anybody explain me how can I achieve this?

Here is my link to full code https://codepen.io/FaizAhmadF/pen/kkkGGX?editors=1010


#2

You should update state inside componentWillReceiveProps, like this:

  componentWillReceiveProps(newProps) {
      this.setState = {
        grid: newProps.grid
      }
  }

#3

I have tried that before.But the changed grid is not reflecting in render.


#4

Sorry :blush: incorretly wrote setState():

    componentWillReceiveProps(newProps) {
      this.setState({
        grid: newProps.grid
      })
    }

#5

Aha!!:grinning:
Thanks bro!!:slight_smile: