ReactJS useState에서 배열로 작업하는 방법.

안녕하세요 개발자님👋



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.



목차


  • 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)

  • 배열에 새 값 추가

    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

    객체 배열에서 특정 객체 업데이트

    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'

    2차원 배열(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.

    2차원 배열의 특정 객체 업데이트(배열의 배열)

    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
  • 첫 번째 친구의 두 번째 취미(핸디)를 바꿔보자.

  • 
        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.



    여기서 마감합니다 👋👋👋

    This is Shareef.
    Live demo
    GitHub repo of this blog
    My Portfolio
    Twitter

    My

    Cover photo by

    좋은 웹페이지 즐겨찾기