How to Push an Element into a State Array in React?

Estimated read time 2 min read

In React, you can push an element into a state array using the concat() method or the spread operator .... Here’s an example of how to push an element into a state array in React:

import React, { useState } from "react";

function MyComponent() {
  const [myArray, setMyArray] = useState(["apple", "banana", "cherry"]);

  const handleClick = () => {
    const newElement = "date";
    // using concat()
    setMyArray(myArray.concat(newElement));
    // or using spread operator
    // setMyArray([...myArray, newElement]);
  };

  return (
    <div>
      {myArray.map((item) => (
        <p key={item}>{item}</p>
      ))}
      <button onClick={handleClick}>Add Element</button>
    </div>
  );
}

In this example, we’re defining a state variable called myArray that contains an array of three strings. We’re using the map() method to render a <p> element for each string, and a “Add Element” button that calls a handleClick function when clicked.

The handleClick function creates a new string element called newElement and uses either the concat() method or the spread operator to create a new array that includes the existing elements plus the new element. We’re then calling the setMyArray function to update the state with the new array.

When the “Add Element” button is clicked, the handleClick function will be called, which will add the new element to the myArray state variable and update the component to re-render with the new element included.

Note that when using the concat() method or the spread operator to add elements to a state array, it’s important to create a new array rather than modifying the original array directly. This ensures that the state is updated correctly and helps avoid unintended side effects.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply