UserList.js
function User({ user, onRemove }) {
const { username, age, id } = user;
return (
<div>
<b>name: {username}</b>
<span> age: {age}</span>
<button
onClick={() => {
onRemove(id);
}}
>
Delete
</button>
</div>
);
}
export default function UserList({ users, onRemove }) {
return (
<div>
{users.map((user) => (
<User user={user} key={user.id} onRemove={onRemove} />
))}
</div>
);
}
onClick={() => {onRemove(id);}}
: 해당 id만 삭제하기 위해 user.id를 매개변수로 넣어서 onRemove 함수 호출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 },
{ id: 2, username: "lee", age: 21 },
{ id: 3, username: "lim", age: 25 },
]);
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));
};
return (
<>
<CreateUser
username={username}
age={age}
onChange={onChange}
onCreate={onCreate}
/>
<UserList users={users} onRemove={onRemove} />
</>
);
}
export default App;