๐ ๋ฐฐ์ด์ ํญ๋ชฉ ์ถ๊ฐ
import React from 'react';
function CreateUser({ username, email, onChange, onCreate }) {
return (
<div>
<input
name="username"
placeholder="๊ณ์ ๋ช
"
onChange={onChange}
value={username}
/>
<input
name="email"
placeholder="์ด๋ฉ์ผ"
onChange={onChange}
value={email}
/>
<button onClick={onCreate}>๋ฑ๋ก</button>
</div>
);
}
export default CreateUser;
import React, { useRef, useState } from 'react';
import UserList from './UserList';
import CreateUser from './CreateUser';
function App() {
const [inputs, setInputs] = useState({
username: '',
email: ''
});
const { username, email } = inputs;
const onChange = e => {
const { name, value } = e.target;
setInputs({
...inputs,
[name]: value
});
};
const users = [
{
id: 1,
username: 'velopert',
email: 'public.velopert@gmail.com'
},
{
id: 2,
username: 'tester',
email: 'tester@example.com'
},
{
id: 3,
username: 'liz',
email: 'liz@example.com'
}
];
const nextId = useRef(4);
const onCreate = () => {
setInputs({
username: '',
email: ''
});
nextId.current += 1;
};
return (
<>
<CreateUser
username={username}
email={email}
onChange={onChange}
onCreate={onCreate}
/>
<UserList users={users} />
</>
);
}
export default App;
๐ก users๋ useState๋ฅผ ์ฌ์ฉํ์ฌ ์ปดํฌ๋ํธ์ ์ํ๋ก์ ๊ด๋ฆฌ
...
const [users, setUsers] = useState([
{
id: 1,
username: 'velopert',
email: 'public.velopert@gmail.com'
},
{
id: 2,
username: 'tester',
email: 'tester@example.com'
},
{
id: 3,
username: 'liz',
email: 'liz@example.com'
}
]);
...
๐ก ๋ถ๋ณ์ฑ์ ์งํค๋ฉด์ ๋ฐฐ์ด์ ์ ํญ๋ชฉ์ ์ถ๊ฐํ๋ ๋ฐฉ๋ฒ
โ ๋ฐฐ์ด์ push, splice, sort ๋ฑ์ ํจ์ ์ฌ์ฉ X, ์ฌ์ฉํด์ผ ํ๋ค๋ฉด ๊ธฐ์กด์ ๋ฐฐ์ด์ ํ๋ฒ ๋ณต์ฌํ ํ ์ฌ์ฉ
๐ฌ spread ์ฐ์ฐ์ ์ฌ์ฉ
...
const nextId = useRef(4);
const onCreate = () => {
const user = {
id: nextId.current,
username,
email
};
setUsers([...users, user]);
setInputs({
username: '',
email: ''
});
nextId.current += 1;
};
...
๐ฌ concat ํจ์ ์ฌ์ฉ
concat ํจ์ : ๊ธฐ์กด์ ๋ฐฐ์ด์ ์์ ํ์ง ์๊ณ , ์๋ก์ด ์์๊ฐ ์ถ๊ฐ๋ ์๋ก์ด ๋ฐฐ์ด์ ์์ฑ
...
const nextId = useRef(4);
const onCreate = () => {
const user = {
id: nextId.current,
username,
email
};
setUsers(users.concat(user));
setInputs({
username: '',
email: ''
});
nextId.current += 1;
};
...