How to Push Array using State in React JS?

Nov 08, 2022 . Admin

Hello Friends,

In this tutorial we will go over the demonstration of how to push an array using state in react js. we will help you to give an example of a push array using state in react js. This article will give you a simple example of a push array using state in react js example. let’s discuss react js array push.

In this example how to push array using state in react js. I will step by step push array using state in react js.

So, let's start following example:

Step 1: Create React JS App

In this step, open your terminal and execute the following command on your terminal to create a new react app:

npx create-react-app reactjs-my-example
Step 2: Create index.js file src/index.js
import {useState} from 'react';
import ReactDOM from 'react-dom';

export default function App() {

    const initialState = [
        {id: 1, name: 'One'},
        {id: 2, name: 'Two'},
    ];

    const [employees, setEmployees] = useState(initialState);

    const handleClick = () => {
        // push object to end of state array
        setEmployees(current => [...current, {id: 3, name: 'Three'}]);
    };

    return (
        <div>
            <div>
                <button onClick={handleClick}>Push to state array</button>
            </div>

            {employees.map((element, index) => {
                return (
                    <div key={index}>
                        <h2>{element.name}</h2>
                    </div>
                );
            })}
        </div>
    );
}
 
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Run React JS App:
npm start

Output:



I hope it can help you...

#React JS