리액트를 배운지 4일이 되었다. 아직 이벤트 핸들러와 상태 끌어올리기 등 머릿 속이 많이 복잡하지만 재밌다. 떠오르는 것들을 다 구현해 보고 싶지만, 내일은 HA가 있는 날.. 왜 이렇게 HA의 날은 빨리 오는지 참 ! class로 투두 리스트 비슷하게 추가 + 삭제버튼을 구현해 보았다. 간단할 수 있는 코드를 장황하게 작성한 것 같아서 리팩토링을 해 보려고 한다. 두 달전쯤 바닐라 자바스크립트로 투두리스트 만들기를 하다가 포기했던 기억이 난다..울렁울렁
아직 스타일 & 구조도 없어서 꾸며주고 가꿔줄 예정이다. class 연습으로 코드를 적었지만.. Hooks의 편리함을 느끼게 해 주는 시간이었다.

import React from "react";
// 나라이름 리스트 정렬
// 인풋에 입력하면 리스트에 추가
// 리스트에 삭제버튼을 만들어서 클릭하면 리스트에서 삭제
class AddAndDelete extends React.Component {
constructor(props) {
super(props)
this.state = {
countries: [
'Korea'
],
inputCountry: ''
}
this.handleAddClick = this.handleAddClick.bind(this);
this.handleDeleteBtn = this.handleDeleteBtn.bind(this);
this.handleOnClick = this.handleOnClick.bind(this);
this.handleEnter = this.handleEnter.bind(this);
this.handleReset = this.handleReset.bind(this);
}
handleEnter(e) {
if (e.code === 'Enter') {
this.setState({ countries: [...this.state.countries, this.state.inputCountry] })
}
}
handleOnClick(event) {
// console.log('엔터 추가버튼 작동')
this.setState({ inputCountry: event.target.value })
}
handleAddClick(e) {
// console.log('추가버튼 작동')
this.setState({ countries: [...this.state.countries, this.state.inputCountry] })
}
handleDeleteBtn(target) {
// console.log('삭제버튼 작동')
const filtered = this.state.countries.filter((country) => country !== target)
this.setState({ countries: filtered })
}
handleReset() {
if (this.state.inputCountry.length !== 0) {
this.state.inputCountry = '';
}
}
render() {
const { countries, inputCountry } = this.state;
// console.log('렌더링 작동')
return (
<section>
<div>
<input
type="text"
value={inputCountry}
onChange={this.handleOnClick}
onKeyDown={this.handleEnter}
/>
<button
onClick={this.handleAddClick}
>
추가
</button>
</div>
<ul>
{countries.map((country, idx) =>
<li key={idx}>{country}
<button onClick={() => this.handleDeleteBtn(country)}>삭제</button>
</li>
)}
</ul>
</section>
)
}
}
export default AddAndDelete;