React Js Add Object to Array
React Js Add Object to Array:In React.js, you can add an object to an array by using the spread operator. First, create a new object that you want to add. Then, use the spread operator (...
) to create a new array that includes the existing objects in the array, along with the new object. This way, the original array remains unchanged, and you have a new array with the added object
Thanks for your feedback!
Your contributions will help us to improve service.
How can I add an object to an array in React.js?
This code is a React component that allows users to add objects to an array. It utilizes the useState hook to manage the state of the array (myArray
) and the input fields (inputName
and inputAge
).
When the user clicks the "Add Object" button, the addObjectToArray
function is called. It creates a new object with the name and age values from the input fields and assigns it a unique ID based on the current length of the array. The spread operator (...
) is used to create a new array that includes the existing objects and the new object, which is then set as the new state using setMyArray
. The input fields are also cleared by setting their values to empty strings.
The handleNameChange
and handleAgeChange
functions update the corresponding state variables whenever the input fields are changed.
Finally, the component renders the input fields, the "Add Object" button, and a list of objects from the array, displaying their name and age. Each object is rendered within a <div>
element with a unique key based on its ID.
Output of React Js Add Object to Array