Author avatar

Vivek Kumar

Removing Items in React

Vivek Kumar

  • Aug 12, 2019
  • 8 Min read
  • 629 Views
  • Aug 12, 2019
  • 8 Min read
  • 629 Views
Web Development
React

Introduction

The React component framework is best known for adding remarkable style animations by offering an effective range of props and libraries. Yes indeed, how many options you provide in terms of animation is one of the key aspects on the grounds of which you evaluate a component framework.

But what if we say that the process of removing the items from the component framework is as important as adding items to it? Yes, during the process of rendering a React component, it is essential that you be able to remove items in a seamless manner whenever necessary. It is going to save you time and minimize the impairment in final rendering caused due to the removal and addition of items, as per demand or requirements.

The removal of the items in the React component is not as hard as it seems to be. But it is essential that you are familiar with the steps, in the correct format, and apply them diligently. In this guide, our purpose is to guide you in the most efficient way so that you can learn to delete items one at a time with merely a click. Once you have finished this guide, I am fully assured that you will become proficient in one of the concrete skills that you are required to hone while working on React - i.e. the removal of items in the simplest way possible. So, with that, let’s get on with it!

A Hypothetical Code Creating `<li>` Element

Let us take a simple, yet quite common, situation where we have a code that builds <li> elements and we are required to delete the concerned elements one at a time simply by clicking. For each of the elements, we have created a delete button and are required to put them into a function before we can delete the concerned items via ID.

The following is the code that we implement in a common term in order to depict the situation mentioned above:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class TodoApp extends React.Component {
    constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.state = {items: [], text: ''};
    }

    render() {
        return (
            <div>
                <h3>TODO</h3>
                <TodoList items={this.state.items} />
                <form onSubmit={this.handleSubmit}>
                    <input onChange={this.handleChange} value={this.state.text} />
                    <button>{'Add #' + (this.state.items.length + 1)}</button>
                </form>
            </div>
        );
    }

    handleChange(e) {
        this.setState({text: e.target.value});
    }

    handleSubmit(e) {
        e.preventDefault();
        var newItem = {
            text: this.props.w +''+this.props.t,
            id: Date.now()
        };
        this.setState((prevState) => ({
            items: prevState.items.concat(newItem),
            text: ''
        }));
    }

    delete(id){          // How does the function know the ID of an item that needs to be deleted and how does it delete the item?
        this.setState(this.item.id)
    }
}

class TodoList extends React.Component {
    render() {
        return (
            <ul>
                {this.props.items.map(item => (
                    <li key={item.id}>{item.text}<button onClick={this.delete.bind(this)}>Delete</button></li>
                ))}
            </ul>
        );
    }
}
jsx

As the code given above seems to be a bit lengthy, they are in their simplest format when applied to the React. The best part is that they are comprehensive and there is no additional component needed to be added while working on the steps of the function required in removing the element.

The Best Way to Tackle the Problem

It is important to note that, during the entire process, you are structuring data within the parent component and then rendering the User Interface (UI) in the Child component. That is the reason why, in order to delete a specific item from the child component, you are required to pass the respective function with the data, trigger the function from the child, and transfer one unique identifier of the list item. Once the item is inside the parent component, you can remove/delete the same item with the help of a unique identifier.

The following are the steps that you are required to follow in order to successfully remove the item.

Step 1: Pass on a function via the parent component with the data, as indicated down below:

1
<TodoList items={this.state.items} _handleDelete={this.delete.bind(this)}/>
jsx

Step 2: Just express the delete function present within the parent component in the following manner:

1
2
3
4
5
delete(id){
    this.setState(prevState => ({
        data: prevState.data.filter(el => el != id )
    }));
}
jsx

Step 3: Next, you are required to call the function from the child component by applying this.props._handleDelete():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class TodoList extends React.Component {
    _handleDelete(id){
        this.props._handleDelete(id);
    }

    render() {
        return (
            <ul>
                {this.props.items.map(item => (
                    <li key={item.id}>{item.text}<button onClick={this._handleDelete.bind(this, item.id)}>Delete</button></li>
                ))}
            </ul>
        );
    }
}
jsx

Take a look at the following working example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class App extends React.Component{
   constructor(){
      super();
      this.state = {
        data: [1,2,3,4,5]
      }
      this.delete = this.delete.bind(this);
   }
   
   delete(id){
      this.setState(prevState => ({
          data: prevState.data.filter(el => el != id )
      }));
   }
   
   render(){
      return(
          <Child delete={this.delete} data={this.state.data}/>
      );
   }
}

class Child extends React.Component{

   delete(id){
       this.props.delete(id);
   }
   
   render(){
      return(
         <div>
           {
              this.props.data.map(el=>
                  <p onClick={this.delete.bind(this, el)}>{el}</p>
              )
           }
         </div>
      )
   }
}

ReactDOM.render(<App/>, document.getElementById('app'))
jsx
1
2
3
4
<script src = "https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src = "https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id = 'app'/>
html

When you take a close glance over the commands that we have mentioned in all the three steps then you are going to find that there are certain steps that naturally raise some questions to mind. One has to be candid enough to identify those questions and seek answers for the same. That is the reason why this guide has been created.

For instance, the most common question that can arise is related to the use of filters in Step 3 in order to filter out data from the array. Well, there can be numerous reasons, but the reason that is prudent to our efforts is that if you return the value true, then it is going to put the concerned value inside a new array. In this case, if you return the value false, then it is going to overlook that specific array value. With the effective use of the filter, it is feasible for us to verify which element has an identical ID. If the ID is an identical one then return with the option false; otherwise, with true. Additionally, the use of filter also prevents the mutation of the state.

Conclusion

I hope that most of your standard queries related to the deletion of the items in React have been answered. All three steps that have been mentioned in the solution are improvised and refined to make things convenient at the time of implementation. We must understand the role of both parent and the child components in the delete function and how the application of filters in the ultimate step can make things a lot easier for you.

Reference

You can further refer the following resource which is also used as a reference for this guide:

0