How to display lists in React Js

Using lists and displaying them is required in almost every app. One of the applications being the menu. We can create lists in React in a similar way as it is created in Javascript. In this tutorial, we will create a simple todo app and see how to correctly display lists in React.

Display lists in React Js

First, we will create an app with one input element and one button element. We will add the onChange and onSubmit event handler and create two functions for that. Look at the code below.

import React, { Component } from 'react'

class App extends Component {
    state={
      todos:[],
      input:""
    }
    handleChange=(e)=>{
      this.setState({input:e.target.value})
    }
    handleSubmit=()=>{
    
    }
  render() {
    return (
      <div>
        <h1>To-Do App</h1>
        <input type="text" placeholder="Type here" onChange={this.handleChange} value={this.state.input}/>
        <button onClick={this.handleSubmit}>Add</button>
      </div>
    )
  }
}

export default App

You can see that we created two state variables- todos and input. We updated the input variable in the handleChange function. Now we will complete our handleSubmit function.

handleSubmit=()=>{
      if(this.state.input!==''){
        const todos=[...this.state.todos];
        const todo={
          id:Math.random(),
          task:this.state.input
        };
        todos.push(todo);
        this.setState({
          todos:todos,
          input:""
        })
      }
    }

The handleSubmit function:

We start by checking if the user has given any input. If he has, then we proceed. In line 3 we make a copy of the todos list using the ES6 spread operator. It is necessary because we should not update the state directly. Instead, we make a copy of the state and make changes there. Following this, we create an object todo having a random id and task. We push this object to the todos variable and set this to the state in setState. We also set input to blank so that after clicking the button, the input field should become empty again.

Displaying list

Now we need to display our todos state. We will write it within curly brackets to print some dynamic things into our JSX. To display a list, we will use javascript’s map function. The map function takes a function as an argument. It will traverse through each element of the list and map it to the function. It returns a new array. The code looks like this:

import React, { Component } from 'react'

class App extends Component {
    state={
      todos:[],
      input:""
    }
    handleChange=(e)=>{
      this.setState({input:e.target.value})
    }
    handleSubmit=()=>{
      if(this.state.input!==''){
        const todos=[...this.state.todos];
        const todo={
          id:Math.random(),
          task:this.state.input
        };
        todos.push(todo);
        this.setState({
          todos:todos,
          input:""
        })
      }
    }
  render() {
    return (
      <div>
        <h1>To-Do App</h1>
        <input type="text" placeholder="Type here" onChange={this.handleChange} value={this.state.input}/>
        <button onClick={this.handleSubmit}>Add</button>
        <ul>
        {this.state.todos.map(item=>{
          return <li>{item.task}</li>
        })}
        </ul>
      </div>
    )
  }
}

export default App

Notice in line 32, we map through each item of the todos list and return its task attribute as a list item in an unordered list.

The output would look like this:

The code works but there is a warning. Each child in a list should have a unique “key” prop. The key property is an important property that we must add when rendering a list of data. This key property helps React to update lists efficiently. Without the key, React would re-render the whole list which is very inefficient. The key property helps React to find out which element has changed and re-renders the elements which did change.

Let us add another function that will delete an element. It will help us understand the use of the key property. We will add a button along with every task to delete it. Look at the code below:

import React, { Component } from 'react'

class App extends Component {
    state={
      todos:[],
      input:""
    }
    handleChange=(e)=>{
      this.setState({input:e.target.value})
    }
    handleSubmit=()=>{
      if(this.state.input!==''){
        const todos=[...this.state.todos];
        const todo={
          id:Math.random(),
          task:this.state.input
        };
        todos.push(todo);
        this.setState({
          todos:todos,
          input:""
        })
      }
    }
    handleDelete=(id)=>{
      const todos=[...this.state.todos];
      const updated=todos.filter(item=>item.id!==id);
      this.setState({todos:updated});
    }
  render() {
    return (
      <div>
        <h1>To-Do App</h1>
        <input type="text" placeholder="Type here" onChange={this.handleChange} value={this.state.input}/>
        <button onClick={this.handleSubmit}>Add</button>
        <ul>
        {this.state.todos.map(item=>{
          return <li key={item.id}>{item.task}<button onClick={()=>{this.handleDelete(item.id)}}>×</button></li>
        })}
        </ul>
      </div>
    )
  }
}

export default App

The handleDelete function:

We created a function handleDelete. In that function, we copy the state to a variable and use javascript’s filter function. Filter function traverses through each element of the list and adds them to a new list only if the condition is satisfied. The new list is returned and stored in a variable- updated. Following this, we update our state to this variable.

The key property:

In line 38, we used the key property and assign the item’s id to it. Since this id is unique to each element, our key has a unique value for each list item. This key helps React to keep track of the changes. It only re-renders the part of the list that is updated. So, if we delete the third item from the list, the entire list does not get re-rendered. That is why the key is important and must be provided.

The output would look like this:

You can see that there is no warning now. The code works perfectly. The item gets removed by clicking the delete button. The whole thing takes place efficiently. This is how you display lists in React.

For more examples, you can visit the official documentation of lists and keys in React.

Leave a Reply

Your email address will not be published. Required fields are marked *