728x90
app.js
import './App.css';
import React from 'react';
import { useRef } from 'react';
import { 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, setUsers] = useState([
{
id: 1,
username: 'velopert',
email: 'public.velopert@gmail.com',
active: false
},
{
id: 2,
username: 'tester',
email: 'tester@example.com',
active: true
},
{
id: 3,
username: 'liz',
email: 'liz@example.com',
active: false
}
]);
const nextId = useRef(4);
const onCreate = () => {
const user = {
id: nextId.current,
username,
email
}
//setUsers([...users, user]) //spread์ฐ์ฐ์ ์ฌ์ฉ
setUsers(users.concat(user)); //concatํจ์ ์ฌ์ฉ - ๊ธฐ์กด ๋ฐฐ์ด์์ x, ์๋ก์ด ์์๊ฐ ์ถ๊ฐ๋ ์๋ก์ด ๋ฐฐ์ด์ ๋ง๋ ๋ค
setInputs({
username: '',
email: ''
});
nextId.current += 1;
};
const onRemove = id => {
// filter : user.id ๊ฐ ํ๋ผ๋ฏธํฐ๋ก ์ผ์นํ์ง ์๋ ์์๋ง ์ถ์ถํด์ ์๋ก์ด ๋ฐฐ์ด์ ๋ง๋ฌ
// user.id๊ฐ id์ธ๊ฒ์ ์ ๊ฑฐ
setUsers(users.filter(user => user.id !== id))
}
const onToggle = id => {
setUsers(
users.map(user =>
user.id === id ? { ...user, active: !user.active } : user
)
)
}
return (
<>
<CreateUser
username={username}
email={email}
onChange={onChange}
onCreate={onCreate}/>
<UserList users={users} onRemove={onRemove} onToggle={ onToggle }/>
</>
)
}
export default App;
UserList.js
import React from 'react';
function User({ user, onRemove, onToggle }) {
return (
<div>
<b style={{
cursor: 'pointer',
color: user.active ? 'green' : 'yellow'
}}
onClick={() => onToggle(user.id)}>
{user.username}
</b>
<b> | { user.email }</b>
<button onClick={() => onRemove(user.id)}> ์ญ์ </button>
</div>
)
}
function UserList({users, onRemove, onToggle}) {
return (
<div>
{users.map(user => (
<User user={user} key={user.id} onRemove={onRemove} onToggle={ onToggle}/> //index = user.id ๋ฐฐ์ด์ ํจ์จ์ ์ผ๋ก ์
๋ฐ์ดํธ ํ๊ธฐ ์ํด์
))}
</div>
)
}
export default UserList;
๐์ฐธ๊ณ ์!!
react.vlpt.us/basic/09-multiple-inputs.html
728x90
'Develop Study ๐ป' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
react / ์ปดํฌ๋ํธ ์ ์ / ํ์๊ฐ์ ํ๋ฉด ๊ตฌํ (0) | 2021.02.01 |
---|---|
React study / sass ์ฐ๊ฒฐ์ Node Sass version 5.0.0 is incompatible with ^4.0.0. (0) | 2021.01.26 |
react study / input์ฒ๋ฆฌํ๊ธฐ / ์ฌ๋ฌ๊ฐ input ์ฒ๋ฆฌ (0) | 2021.01.23 |
react study / ์ปดํฌ๋ํธ์์ ๊ฐ ๋ฐ์ ๋ฐ๊พธ๊ธฐ (0) | 2021.01.22 |
react study / props ๊ฐ๋ ์ดํด (0) | 2021.01.22 |