mercredi 28 août 2019

setState not re-rendering react component inside array

I'm trying to create a react app that adds a react component when pressing a button a then re-renders it. I'm using an array of p elements inside state as a test. The event handler function uses setState to modify the array but for some reason it does not re-renders de component so the change (the new element) is not showed in the screen. What I'm doing wrong?

import React, {Component} from "react";

export default class Agenda extends React.Component{

  constructor(props){

    super(props);

    this.list = [];

    this.state = {

      list:[]

    };

    this.addItem = this.addItem.bind(this);

    const items = ["Hola Mundo 1","Hola Mundo 2","Hola Mundo 3"];

    const itemComponent = items.map((item) => 
      <p>{item}</p>
    );

    this.list = itemComponent;
    this.state.list = itemComponent; 

  }

  addItem(){

    //Adds a new paragraph element at the end of the array
    this.list[3]= <p>Hola Mundo 4</p>;

    this.setState(

      {
        list: this.list
      }
    );

  }

  render(){


    return(

      <div id={this.props.id} className={this.props.className}> 


        {this.state.list}

        <button onClick={this.addItem}>

          Add item

        </button>

      </div>

    );

  }
}




Aucun commentaire:

Enregistrer un commentaire