반응형
App.js
import React, { useRef, useState } from "react";
import Hello from "./Hello.js";
import "./App.css";
import Wrapper from "./Wrapper.js";
import Counter from "./Counter.js";
import InputSample from "./InputSample.js";
import UserList from "./UserList.js";
import CreateUser from "./CreateUser.js";
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: true
},
{
id: 2,
username: "tester",
email: "tester@example.com",
active: false
},
{
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]);
setInputs({
username: "",
email: ""
});
nextId.current += 1;
};
const onRemove = 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 }) {
const { username, email, id, active } = user;
return (
<div>
<b
style={{ color: active ? "green" : "black", cursor: "pointer" }}
onClick={() => onToggle(id)}
>
{username}
</b>{" "}
<span>({email})</span>
<button onClick={() => onRemove(id)}>삭제</button>
</div>
);
}
function UserList({ users, onRemove, onToggle }) {
return (
<div>
{users.map(user => (
<User
user={user}
key={user.id}
onRemove={onRemove}
onToggle={onToggle}
/>
))}
</div>
);
}
export default UserList;
반응형
'2020 > React' 카테고리의 다른 글
react #배열 항목 제거하기 (0) | 2020.04.01 |
---|---|
React 새로운 배열 추가하기 (0) | 2020.03.31 |
React 배열 렌더링하기 (0) | 2020.03.31 |
React useRef로 Dom 선택하기 (0) | 2020.03.31 |
InputSample (0) | 2020.03.30 |