import React,{useState} from "react";
const friendsArray = [
{
name:"Lalit",
age: 23,
},
{
name:"Neha",
age: 22,
},
{
name:"Piyush",
age: 20,
},
]
function Arrex(){
const [arr,setArr] = useState(friendsArray)
const handleclick=()=>{
setArr((prevArr)=>[
...prevArr,
{
name:"Shubham",
age:25,
}])
}
const handleupdate=()=>{
setArr([
...arr,
arr[0].name="Purohit",
arr[1].name="Sharma",
],
)
}
return(
<div>
<h2>Adding a new value to array</h2>
<ul>
{arr.map((friend,index)=>(
<li key={index}>name: {friend.name}<br/>age: {friend.age}</li>
))}
</ul>
<button onClick={handleclick}>Add New</button>
<button onClick={handleupdate} >Update</button>
</div>
)
}
export default Arrex;
[Result After click on update ]
[Result Before click on update]
I am a new learner of react js and i was practices that concept for better understanding but when i update the array the output is get but the null object is increases by two i try many time but not solve the issue i to get the proper output in this code.
>Solution :
Problem with handleupdate function. If you want to update a specific element in an array, you must use the setArr method correctly.
import React, { useState } from "react";
const friendsArray = [
{
name: "Lalit",
age: 23,
},
{
name: "Neha",
age: 22,
},
{
name: "Piyush",
age: 20,
},
];
function Arrex() {
const [arr, setArr] = useState(friendsArray);
const handleclick = () => {
setArr((prevArr) => [
...prevArr,
{
name: "Shubham",
age: 25,
},
]);
};
const handleupdate = () => {
// Update specific elements in the array
setArr((prevArr) => [
{
...prevArr[0],
name: "Purohit",
},
{
...prevArr[1],
name: "Sharma",
},
...prevArr.slice(2), // Keep the rest of the array unchanged
]);
};
return (
<div>
<h2>Adding a new value to the array</h2>
<ul>
{arr.map((friend, index) => (
<li key={index}>
name: {friend.name}
<br />
age: {friend.age}
</li>
))}
</ul>
<button onClick={handleclick}>Add New</button>
<button onClick={handleupdate}>Update</button>
</div>
);
}
export default Arrex;
Changed the logic in the handleupdate function to correctly update certain elements in the array. It preserves the properties of the first two elements (names in this case) and updates them accordingly, but the rest of the array remains unchanged. This allows you to update specific elements within React’s arr state.