React 배열에 항목 수정하기

G-NOTE·2021년 5월 25일
0

React

목록 보기
4/27

UserList.js

function User({ user, onRemove, onToggle }) {
  const { username, age, id, active } = user;
  return (
    <div>
      <b
        onClick={() => {
          onToggle(id);
        }}
        style={{ color: active ? "red" : "black", cursor: "pointer" }}
      >
        name: {username}
      </b>
      <span> age: {age}</span>
      <button
        onClick={() => {
          onRemove(id);
        }}
      >
        Delete
      </button>
    </div>
  );
}

export default function UserList({ users, onRemove, onToggle }) {
  return (
    <div>
      {users.map((user) => (
        <User
          user={user}
          key={user.id}
          onRemove={onRemove}
          onToggle={onToggle}
        />
      ))}
    </div>
  );
}
<b
  onClick={() => {
    onToggle(id);
  }}
  style={{ color: active ? "red" : "black", cursor: "pointer" }}
>
  name: {username}
</b>
  • 클릭 이벤트가 발생했을 때 id를 매개변수로 onToggle 함수 호출

App.js

import { useRef, useState } from "react";
import UserList from "./UserList";
import CreateUser from "./CreateUser";

function App() {
  const [inputs, setInputs] = useState({
    username: "",
    age: "",
  });

  const { username, age } = inputs;

  const [users, setUsers] = useState([
    { id: 1, username: "bae", age: 22, active: true },
    { id: 2, username: "lee", age: 21, active: false },
    { id: 3, username: "lim", age: 25, active: false },
  ]);

  const nextId = useRef(4);
  const onChange = (e) => {
    const { name, value } = e.target;
    setInputs({
      ...inputs,
      [name]: value,
    });
  };

  const onCreate = () => {
    // 새로운 user 객체 생성
    const user = {
      id: nextId.current,
      username,
      age,
    };

    setUsers([...users, user]);

    setInputs({
      username: "",
      age: "",
    });
    nextId.current += 1;
  };

  const onRemove = (id) => {
    setUsers(users.filter((user) => user.id !== id));
  };

  const onToggle = (id) => {
    // 일치하는 user의 active 상태를 toggle
    setUsers(
      users.map((user) =>
        user.id === id ? { ...user, active: !user.active } : user
      )
    );
  };

  return (
    <>
      <CreateUser
        username={username}
        age={age}
        onChange={onChange}
        onCreate={onCreate}
      />
      <UserList users={users} onRemove={onRemove} onToggle={onToggle} />
    </>
  );
}
export default App;
profile
FE Developer

0개의 댓글