React에서 Hook을 사용하는 State의 배열 추가/삭제/수정
2020. 12. 3. 18:11ㆍ서버 프로그래밍
맨날 기억이 안난다. ㅠㅠ
const [joinList, setJoinList] = useState(['Oliver' ,'Harry' ,'George' ,'Noah' ,'Jack' ,'Jacob' ]);
//Add item
const addJoinPeople = (e) =>{
let name = e.target.value;
setJoinList([...joinList, name]);
};
//Delete item
const RemovePeople = (e) =>{
let name = e.target.value;
setJoinList(joinList.filter((e)=>(e !== name)))
};
medium.com/javascript-in-plain-english/how-to-add-to-an-array-in-react-state-3d08ddb2e1dc
tyindpgood.medium.com/add-delete-item-from-state-array-in-react-hook-9d7f73d66d80
const [datas, setDatas] = useState([
{
id: 1,
name: "john",
gender: "m",
},
{
id: 2,
name: "mary",
gender: "f",
},
]);
const updateFieldChanged = (name, index) => (event) => {
let newArr = datas.map((item, i) => {
if (index == i) {
return { ...item, [name]: event.target.value };
} else {
return item;
}
});
setDatas(newArr);
};
return (
<React.Fragment>
{datas.map((data, index) => {
<li key={data.name}>
<input
type="text"
name="name"
value={data.name}
onChange={updateFieldChanged("name", index)}
/>
</li>;
<li key={data.gender}>
<input
type="text"
name="gender"
value={data.gender}
onChange={updateFieldChanged("gender", index)}
/>
</li>;
})}
</React.Fragment>
);