React doesn't render all components of array

1685 views javascript
6

I want to dynamically add Components, after clicking the "add" button. For that, I created an array that consists of all the components, and add them on click.

My problem is, that it only renders one component, even though it consists of several ones.

My code looks like this:

class QuestionBlock extends React.Component {
    constructor(props) {
        super(props);
        this.state = {answersArray: []};
    }

    addPossibleAnswer() {
        this.state.answersArray.push(
            <PossibleAnswers id={this.state.answersArray.length + 1}/>
        )
        this.forceUpdate();
    }

    componentWillMount() {
        this.state.answersArray.push(
            <PossibleAnswers id={this.state.answersArray.length + 1}/>
        )
    }

    render() {
        console.log(this.state.answersArray) // Grows after adding componenets, but they are not rendered.
        return (
            <div>
                {this.state.answersArray}
                <AddPossibleAnswer addPossibleAnswer={() => this.addPossibleAnswer()} />
            </div>
        );
    }
}

If you see what I did wrong, I'd be really glad if you could help me out!

answered question

Its because you're mutating the state.

1 Answer

8

You don't interact with state like you do. You need to use this.setState:

this.setState(prevState => ({answersArray: prevState.answersArray.concat([<PossibleAnswers id={prevState.answersArray.length + 1}])}));

posted this

Have an answer?

JD

Please login first before posting an answer.