React doesn't render all components of array

1685 views javascript

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) {
        this.state = {answersArray: []};

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

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

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

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


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?


Please login first before posting an answer.