[스터디]리액트를 다루는 기술 – 컴포넌트 반복

자바스크립트 배열의 map(), filter()함수를 이용하여 객체를 복제한 뒤 데이터를 처리한다.

// 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);

    const onChange = e => setInputText(e.target.value);
    const onClick = () => {
        const nextNames = names.concat({
            // 배열의 push를 쓰지 않고, concat을 쓰도록 한다. push는 기존 배열을 변경하고, concat은 새로운 배열을 만들어준다.
            id: nextId,
            text: inputText
        });
        setNextId(nextId + 1);
        setNames(nextNames);
        setInputText('');
    };
    const onRemove = id => {
        const nextNames = names.filter(name => name.id !== id); // filter 함수를 사용하여 삭제하고자 하는 요소를 제거한다.
        setNames(nextNames);
    };

    const nameList = 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>{nameList}</ul>
        </>
    );
};

export default IterationSample;

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다