Rendering a list in React JS

31st Jul 18
Thumbnail

In this article I go through rendering a list in React

You can use the map function on the state which will return a new array. Adding map function to the render method, React will try to render the individual elements of the returned array if in JSX format.  Rather than referencing this.state you reference the individual element within the map method, in the below example named person. 

 let people = null;
  if(this.state.showPeople){
    people = (
      <div >
        {this.state.persons.map(person => {
          return <Person 
                  name={person.name} 
                  age={person.age}/>
        })}
     </div>
    );
  }

 

I want to add an event handler to the person card that deletes that person on a click.  Firstly I add a new event handler function called deletePersonHandler.  I add a click attribute and within the parenthesis I added an anonymous function which returns the deletePersonHandler function.  The deletePersonHandler has the map element index as an argument.  Then within the deletePersonHandler I splice the persons array which effectively removes that element from the array and followed by updating the state.

  people = (
      <div >
        {this.state.persons.map((person, index) => {
          return <Person 
                  click={()=>this.deletePersonHandler(index)}
                  name={person.name} 
                  age={person.age}/>
        })}
     </div>
    );
deletePersonHandler = (personIndex) => {
const people = this.state.persons;
people.splice(personIndex, 1);
this.setState({persons: people})
}

But splicing the state's 'person' array is not considered best practice.  It is best to make a copy of the state array before altering it.  To make a copy of an array you can use the function slice.  The javascript slice method returns a copy of an array or a portion of the array and the original array will not be altered.  If you do not provide any arguments to the slice function you make a copy of the complete array.

deletePersonHandler = (personIndex) => {
    const people = this.state.persons.slice();
    people.splice(personIndex, 1);
    this.setState({persons: people})
}

Another way of making a copy of the array is by using ES6 spread operator.  

const people = [...this.state.persons];

And by following this approach you will be updating the state in an immutable fashion, which is recommended. 

I have recently completed my apprenticeship.  I am currently building the API to a React JS site using Firebase.