이제 filter 함수를 사용하여 IterationSample 컴포넌트의 항목 제거 기능을 구현해 봅시다. HTML 요소를 더블클릭할 때 사용하는 이벤트 이름은 onDoubleClick입니다. onRemove라는 함수를 만들어서 각 li 요소에 이벤트 등록을 해 주세요.

    IterationSample.js

    import React, { useState } from 'react';
     
    const IterationSample = () => {
      const [names, setNames] = useState([
        { id: 1, text: '눈사람' },
        { id: 2, text: '얼음' },
        { id: 3, text: '' },
        { id: 4, text: '바람' }
      ]);
      const [inputText, setInputText] = useState('');
      const [nextId, setNextId] = useState(5); // 새로운 항목을 추가할  사용할 id
     
      const onChange = e => setInputText(e.target.value);
      const onClick = () => {
        const nextNames = names.concat({
          id: nextId, // nextId 값을 id 설정하고
          text: inputText
        });
        setNextId(nextId + 1); // nextId 값에 1 더해 준다.
        setNames(nextNames); // names 값을 업데이트한다.
        setInputText(''); // inputText 비운다.
      };
      const onRemove = id => {
        const nextNames = names.filter(name => name.id != = id);
        setNames(nextNames);
      };
      const namesList = names.map(name => (
        <li key={name.id} onDoubleClick={() => onRemove(name.id)}>
          {name.text}
        </li>
      ));
      return (
        <>
          <input value={inputText} onChange={onChange} />
          <button onClick={onClick}>추가</button>
          <ul>{namesList}</ul>
        </>
      );
    };
     
    export default IterationSample;

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.