Mohammed Nadeem Shareef
Posted on May 21, 2021
Hello Developers👋
ReactJS introduce Hooks in React 16.8. And since then the most used hook is "useState" || "useEffect"
In this blog, We will take a look at how work with Arrays and "useState" hook.
Table Of Contents
- Adding a new value to Array
- Updating a specific object in Array of objects
- Adding a new value in two dimensional array(array in Array)
- Updating a specific object in two dimensional array(array in Array)
Adding a new value to Array
Let's first create a friends array we will have two properties, name, and age
const friendsArray = [
{
name: "John",
age: 19,
},
{
name: "Candy",
age: 18,
},
{
name: "mandy",
age: 20,
},
];
Now let's work with this array and useState
import { useState } from "react";
const App = () => {
const [friends, setFriends] = useState(friendsArray); // Setting default value
const handleAddFriend = () => {
...
};
return (
<main>
<ul>
// Mapping over array of friends
{friends.map((friend, index) => (
// Setting "index" as key because name and age can be repeated, It will be better if you assign uniqe id as key
<li key={index}>
<span>name: {friend.name}</span>{" "}
<span>age: {friend.age}</span>
</li>
))}
<button onClick={handleAddFriend}>Add Friends</button>
</ul>
</main>
);
};
export default App;
- Here, we are mapping over friends array and displaying it.
- Let's now see How to add new values to this array
const handleAddFriend = () => {
setFriends((prevFriends) => [
...prevFriends,
{
name: "Random Friend Name",
age: 20, // Random age
},
]);
};
Here, setState let us define an anonymous function that has its previews state as an argument to the function, then we are using spread operator to get our all previews value(state) now after this we can add our new value.
but this method only adds new value to the end of the array. And this brings me to our next topic
Updating a specific object in Array of objects
Let say you have an array of friends and you want to update the specific friend name || age.
Updating our friend's array
const friendsArray = [
{
id: 1,
name: "handy",
age: 19,
},
{
id: 2,
name: "Candy",
age: 18,
},
{
id: 3,
name: "mandy",
age: 20,
},
];
- Now we have a unique id to update only one specific object
- Add a button.
...
<button onClick={handleSecondFriend}>Change Second Name</button>
...
- Here I am targeting only a second friend name but you can how every change it to target dynamic value(id).
- Let's work on *handleSecondFriend function.
const handleSecondFriend = () => {
setFriends(
friends.map((friend) =>
// Here you accept a id argument to the function and replace it with hard coded 🤪 2, to make it dynamic.
friend.id === 2
? { ...friend, name: "Changed Name" }
: { ...friend }
)
);
};
- Here we are changing the object that matches the id or the hardcoded value '2'
Adding a new value in two dimensional array(array in Array)
Let's update our array of friends again 😅
This time I am adding likes or hobbies also 🤪
const friendsArray = [
{
id: 1,
name: "handy",
age: 19,
hobbies: ["Cooking", "Reading"],
},
{
id: 2,
name: "Candy",
age: 18,
hobbies: ["Bathing", "Eating"],
},
{
id: 3,
name: "mandy",
age: 20,
hobbies: ["Making Videos", "Dancing", "Coding"],
},
];
Now everything will be more interesting to work 🤩.
Let's display hobbies
...
const [friends, setFriends] = useState(friendsArray);
const handleThirdFriendHobby = () => {
...
};
return (
<ul>
{friends.map((friend) => (
// I am no longer using index as key, as I have unique id value.
<li key={friend.id}>
<span>name: {friend.name}</span>{" "}
<span>age: {friend.age}</span>
<br />
<span>Hobbies</span>
<ul>
{friend.hobbies.map((hobby) => (
<li>{hobby}</li>
))}
</ul>
</li>
))}
<button onClick={handleThirdFriendHobby}>Add Hobby to mandy</button>
</ul>
);
...
- Now let's add || modify 3rd friend hobby.
const handleThirdFriendHobby = () => {
setFriends(
friends.map((friend) =>
friend.id === 3
? {
...friend,
hobbies: [...friend.hobbies, "Random Hobby"],
}
: { ...friend }
)
);
};
- How easy and interesting it was, but as previews, this only adds a new hobby to the end of the array, and this brings us to our next topic.
Updating a specific object in two dimensional array(array in Array)
Let's update our array of friends again 😅
This time I am adding ids for hobbies 🤪
const friendsArray = [
{
id: 1,
name: "handy",
age: 19,
hobbies: [
{ text: "Cooking", id: 1 },
{ text: "Reading", id: 2 },
],
},
{
id: 2,
name: "Candy",
age: 18,
hobbies: [
{ text: "Bathing", id: 1 },
{ text: "Eating", id: 2 },
],
},
{
id: 3,
name: "mandy",
age: 20,
hobbies: [
{ text: "Making Videos", id: 1 },
{ text: "Dancing", id: 2 },
{ text: "Coding", id: 3 },
],
},
];
- Displaying the hobbies is as same as previews
- Let's change the second hobby of the first friend(handy).
const handleFirstFriendHobby = () => {
setFriends(
friends.map((friend) =>
friend.id === 1
? {
...friend,
hobbies: friend.hobbies.map((hobby) =>
// You can replace 2 with your dynamic value
hobby.id === 2
? { ...hobby, text: "Random Hobby" }
: { ...hobby }
),
}
: { ...friend }
)
);
};
Here we are mapping hobbies inside another mapping function, and you can replace the hard-coded 2 with dynamic value.
Closing here 👋👋👋
This is Shareef.
Live demo
GitHub repo of this blog
My Portfolio
Twitter ShareefBhai99
My other BlogsCover photo by Codevolution
Posted on May 21, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.