6.4.2 데이터 추가 기능 구현하기

    이제 새로운 이름을 등록할 수 있는 기능을 구현해 봅시다.

    우선 ul 태그의 상단에 inputbutton을 렌더링하고, input의 상태를 관리해 보세요.

    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 namesList = names.map(name => <li key={name.id}>{name.text}</li>);
      return (
        <>
          <input value={inputText} onChange={onChange} />
          <button>추가</button>
          <ul>{namesList}</ul>
        </>
      );
    };
     
    export default IterationSample;

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