Solution
To add an object to an array in react js, use the push()
method it will add new objects at the end of array. You have to just pass your object into push method.
push()
Method
The push()
method adds one or more elements to the end of an array and returns the new length of the array.
Snippet
In this snippet, we will see short example to add object into an array using push()
method.
const arr = [{
id: 1,
name: "infinitbility"
}];
arr.push({id: 2, name: "aGuideHub"});
console.log(arr); // (2) [{…}, {…}]
Example
In this example, we will create an array state with some data and add object into array state in useEffect
hook, and show the array value in the UI.
Let’s start coding…
App.js
import React, { useEffect, useState } from "react";
export default function App() {
const [domainsList, setDomainsList] = useState([{
id: 1,
name: "infinitbility"
}]);
useEffect(() => {
let arr = [...domainsList];
arr.push({id: 2, name: "aGuideHub"});
setDomainsList(arr);
}, []);
return (
<div className="App">
<h1>{`Print the Array of object`}</h1>
<p>{JSON.stringify(domainsList)}</p>
</div>
);
}
Output