Responsive Advertisement

How to push in an array object with useState in ReactJS?

 

useState Hook ReactJS

How to push in an array object with useState in ReactJS?

To push an item into an array object using useState in ReactJS, you need to follow the following steps:

1. Create a state variable with useState, initializing it with an array:

const [items, setItems] = useState([]);
To add a new item to the array, use the spread operator ... to create a new array with the existing items plus the new one, and pass it to the setItems function:
jsx
Copy code
setItems([...items, newItem]);

where newItem is the item you want to add to the array.

2. Here's an example code snippet:

import React, { useState } from 'react';

function App() {
  const [items, setItems] = useState([]);

  const handleClick = () => {
    const newItem = { name: 'New Item' };
    setItems([...items, newItem]);
  };

  return (
    <div>
      <button onClick={handleClick}>Add Item</button>
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}
export default App;

In this example, a new item is created with the name "New Item" when the button is clicked, and it is added to the items array using the setItems function. The items array is then rendered as an unordered list.


Post a Comment

0 Comments