CreateUser.js
export default function CreateUser({ username, age, onChange, onCreate }) {
return (
<div>
<input
name="username"
placeholder="계정명"
onChange={onChange}
value={username}
/>
<input name="age" placeholder="나이" onChange={onChange} value={age} />
<button onClick={onCreate}>등록</button>
</div>
);
}
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 onChange = (e) => {
const { name, value } = e.target;
setInputs({
...inputs,
[name]: value,
});
};
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 onCreate = () => {
// 새로운 user 객체 생성
const user = {
id: nextId.current,
username,
age,
};
setUsers([...users, user]);
setInputs({
username: "",
age: "",
});
nextId.current += 1;
};
return (
<>
<CreateUser
username={username}
age={age}
onChange={onChange}
onCreate={onCreate}
/>
<UserList users={users} />
</>
);
}
export default App;
[name]
: name이 가리키고 있는 것이 username이면 계정명이 바뀌고 age면 나이가 바뀐다. const onCreate = () => {
// 새로운 user 객체 생성
const user = {
id: nextId.current,
username,
age,
};
setUsers([...users, user]);
// onCreate 됐을 때 input에 있는 값 지우기
setInputs({
username: "",
age: "",
});
nextId.current += 1;
};