- 배열에 항목 추가하기
function App() {
const nextId = useRef(4);
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:'carllis',
email:'oterte@naver.com'
},
{
id:2,
username:'pocket',
email:'oterte2891@gmail.com'
},
{
id:3,
username:'Liz',
email:'liz@example.com'
}
])
const onCreate = () =>{
const newUser = {
id:nextId.current,
username,
email,
}
setUsers([
...users,
newUser
]
)
setInputs({
username:'',
email:''
})
nextId.current += 1;
}
return (
<>
<CreateUser username={username} email={email} onChange={onChange} onCreate={onCreate}/>
<UserList users={users}/>
</>
);
}
export default App;
- 배열에 항목 제거하기
function User({user, onRemove}){
const {username, email, id} = user
return(
<div>
<b>{username}</b><span>({email})</span>
{}
{}
{}
{}
<button onClick={() => onRemove(id)}>삭제</button>
</div>
)
}
export default function UserList({users, onRemove}) {
console.log(users)
return (
<div>
{
users.map(
user => (
<User
user={user}
key={user.id}
onRemove={onRemove}/>)
)
}
</div>
)
}
const onRemove = (id) =>{
setUsers(users.filter(user => user.id !== id))
}
return (
<>
<CreateUser username={username} email={email} onChange={onChange} onCreate={onCreate}/>
<UserList users={users} onRemove={onRemove}/>
</>
);
- 배열 항목 수정하기
- 맨 처음 기존 배열에 수정할 수 있는 값 넣어주기
const [users,setUsers] =useState([
{
id:1,
username:'carllis',
email:'oterte@naver.com',
active:true
},
{
id:2,
username:'pocket',
email:'oterte2891@gmail.com',
active:true
},
{
id:3,
username:'Liz',
email:'liz@example.com',
active:false
}
])
- 사용하고 싶은 위치에 props로 그 값을 넣어 원하는 방법으로 사용
function User({user, onRemove}){
const {username, email, id , active} = user
return(
<div>
<b style={{
color: active ? 'green' : 'black',
cursor:'pointer'
}}>{username}</b><span>({email})</span>
<button onClick={() => onRemove(id)}>삭제</button>
</div>
)
}
const onToggle = id => {
setUsers(users.map(
user=>user.id === id
?{...user,active:!user.active}
:user
));
}