React Create Dynamic Array of Objects
React is to create and manipulate arrays of objects, which can represent data such as items in a list, products in a cart, or posts in a blog. In this article, we will learn how to create dynamic arrays of objects in React using the useState hook, which allows us to manage state in functional components. We will also see how to add, remove, and update objects in the array using various methods such as push, splice, and map.




Thanks for your feedback!
Your contributions will help us to improve service.
How can I Dynamically Add Object to Array React js?
In React.js, you can dynamically push or add items to an array of objects using the useState hook and the spread operator. First, create a state variable using useState, initializing it with the initial array of objects. To add a new item, create a copy of the array using the spread operator, and add the new item to the copy. Finally, update the state variable with the updated array. This allows React to re-render the component and reflect the changes. By following this approach, you can dynamically push or add items to an array of objects in React.js
Adding Item to list Dynamically in React
xxxxxxxxxx
<script type="text/babel">
const { useState } = React;
function App() {
const [objects, setObjects] = useState([]);
const [inputValues, setInputValues] = useState({
name: '',
age: ''
});
const addObject = (e) => {
e.preventDefault();
// create a new object with input values
const newObj = {
name: inputValues.name,
age: inputValues.age
};
// add the object to the array
setObjects([...objects, newObj]);
// clear the input fields
setInputValues({
name: '',
age: ''
});
};
const handleInputChange = (e) => {
const { name, value } = e.target;
setInputValues({
...inputValues,
[name]: value
});
};
return (
<div className='container'>
<h3>React Js Create Array of object Dynamically | push item to array of object </h3>
<form onSubmit={addObject}>
<div>
<label>Name:</label>
<input
type='text'
name='name'
value={inputValues.name}
onChange={handleInputChange}
required
/>
</div>
<div>
<label>Age:</label>
<input
type="number"
name="age"
value={inputValues.age}
onChange={handleInputChange}
required
/>
</div>
<div>
<button type="submit">Add Object</button>
</div>
</form>
<ul>
{objects.map((obj, index) => (
<li key={index}>
Object {index + 1} - Name: {obj.name}, Age: {obj.age}
</li>
))}
</ul>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>