Blueprint
Blueprint

Reputation: 442

child component's props not updating when parent's state updates

I am making a Connect-Four game. every column (component) recieves the current player color as a prop from the parent component. i have a callback function in every column that changes the current player state every time a column is being clicked, but for some reason the columns won't accept the new parent state as an updated prop.

class App extends React.Component {
    constructor() {
        super()

        this.state = {
            currentPlayer: 'red',
            board: null,
        }
    }

    changePlayer = () => {
        this.state.currentPlayer === 'red' ?
            this.setState({
                currentPlayer: 'yellow'
            }) :
            this.setState({
                currentPlayer: 'red'
            })
    }

    componentDidMount() {
        let newBoard = [];
        for(let x = 0; x < 7; x++) {
            newBoard.push(<Column 
                key={`column ${x}`} 
                currentPlayer={this.state.currentPlayer} 
                changePlayer={this.changePlayer}
                x={x} 
            />)
        }

        this.setState({
            board: newBoard,
        })
    }

    render() {
        return(
            <div className="app">
                <div className="board">
                    {this.state.board}
                </div>
            </div>
        )
    }
}
class Column extends React.Component {
    constructor(props) {
        super(props)

        this.state = {
            colors: ['white', 'white', 'white', 'white', 'white', 'white']
        }
    }

    handleClick = () => {
        for(let i = 0; i < 6; i++) {
            if(this.state.colors[i] === 'white') {
                let newColors = this.state.colors;
                newColors[i] = this.props.currentPlayer;
                this.setState({
                    colors: newColors
                })
                break;
            }
        }

        this.props.changePlayer();
    }

    render() {
        let column = [];
        for(let y = 5; y >= 0; y--) {
            column.push(<Tile 
                key={`${this.props.x},${y}`} 
                x={this.props.x} 
                y={y} 
                color={this.state.colors[y]}
            />)
        }

        return(
            <div className="column" onClick={() => this.handleClick()}>
                {column}
            </div>
        )
    }
}

i am assuming the issue is with the fact that the columns are created with componentDidMount lifecycle hook? how could i fix that without altering too much of the code structure if that's the case?

Upvotes: 3

Views: 974

Answers (1)

Mos&#232; Raguzzini
Mos&#232; Raguzzini

Reputation: 15821

It is not clear where your code fails, but:

    // Here you are setting a reference to the array in state, not a copy
    let newColors = this.state.colors;
    // Here you are mutating directly the state (antipattern!)
    newColors[i] = this.props.currentPlayer;
    // You are setting the reference to the array that has already mutated (prevState === nextState)
    this.setState({
     colors: newColors
    });

Instead do:

    // Make a COPY of your array instead of referencing it
    let newColors = [...this.state.colors];
    // Here you are mutating your CLONED array
    newColors[i] = this.props.currentPlayer;
    // You are setting the NEW color array in the state
    this.setState({
     colors: newColors
    });

Ok, I've got your issue.

Change in App.js:

for(let x = 0; x < 7; x++) {
    newBoard.push(<Column 
        key={`column ${x}`}
        // retrieve value with a method as below 
        currentPlayer={() => this.state.currentPlayer} 
        changePlayer={this.changePlayer}
        x={x} 
    />)
}

In Columns.js:

newColors[i] = this.props.currentPlayer();

Working example:

https://stackblitz.com/edit/react-zzoqzj?file=Column.js

Upvotes: 3

Related Questions