Best ways to add an element to an array in React state with examples

This is a short tutorial on how to add an object to an array of objects in React. And also how to update the array of objects into react state component.

This tutorial explains how to push an element to an array of elements in React with code examples.

In this section, we will learn how to add an object to an array of objects in React. ReactJS is a JavaScript UI library for building user interfaces. It is maintained by Facebook and Instagram.

ReactJS add an object element to an array at the start or end or any index position with code examples:

How to add an object to an array in ReactJS

In this article, I’m going to show you how to add an object to an array in ReactJS. It’s very easy once you know the syntax. We’ll look at removing a list of items, removing by index, and removing by key.

  • Create a new array with the object you want to add and the rest of the array.
  • The elements are added to an array in javascript react
    • Add an element to the beginning of an array
    • Add an element to the End of an array
    • Add an element to any position in the array

Let’s see how we can implement these two approaches with array methods in React

  • The First approach mutates the array using the splice method This approach mutates the original array and returns the original array by adding an element at a specific index position

    • Find the element of an array using the indexOf method
    • splice🔗 method adds the element to the index position.
var numbers = [1, 2, 3];
numbers.splice(2, 0, 5); // add  5 at index-2 position and array positions are shifted
console.log(numbers);

Output:

[1,2,3,5]
  • Second way using the Array push method to add the element to the end of an array

    The array push method adds the element to the end of an array. It mutates the original array

let numbers = [1, 2, 3, 4];
numbers.push(5);
console.log(numbers);

Output:

[1,2,3,4,5]
  • Third way using the Array unshift method to add the element at the start of an array

    The array unshift method adds the element to the beginning of an array. It mutates the original array and shifts the positions

let numbers = [1, 2, 3, 4];
let element = numbers.unshift(-1, 0);
console.log(numbers);

Output:

[-1,0,1,2,3]

How to add an element to an array in React state?

React components maintain the state that contains the array of elements. The below example adds an element to an array of elements from a component state. Created a button to add an element to an array in a state

Used the push method to add an element to an array in the state, You can use one of the above approaches to add an element to an array.

  • Defined the empty array in a react state using the constructor
  this.state = {
     names:[],
     name:"
   };
   ```

On button clic, It adds user-entered names into an array using push. next, Finally, update the state after adding the element using this.setState method

const names = [...this.state.names];
names.push(this.state.name);
this.setState({ names: names });

Here is an example

import React, { Component } from "react";
import { render } from "react-dom";

class App extends Component {
  constructor() {
    super();
    this.state = {
      names: [],
      name: "",
    };
  }
  handleChange = (event) => {
    this.setState({ name: event.target.value });
  };
  deleteElement = (index) => {
    this.state.names.splice(index, 1);
    this.setState({ names: this.state.names });
    console.log(index);
  };
  addElement = () => {
    const names = [...this.state.names];
    names.push(this.state.name);
    this.setState({ names: names });
    this.setState({ name: "" });
  };

  render() {
    const print = () => {
      return this.state.names.map((item, index) => {
        return (
          <div key={item}>
            <span>{item} </span>
            <button onClick={() => this.deleteElement(index)}>Delete</button>
          </div>
        );
      });
    };

    return (
      <div>
        <input
          type="text"
          value={this.state.name}
          onChange={this.handleChange}
        />
        <button onClick={this.addElement}>Add Element</button>
        <h3>List of elements</h3>
        {print()}
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

Conclusion

Learned multiple ways to react with components

  • add an element from an array in React
  • add an element from the state array in react