-
TIL-2024.04.28 - React - 004. React 에서의 반복 (+추가&제거)> Frontend/React 2024. 4. 28. 22:22
질문
1. React에서 반복문을 사용하는 방법
Map 을 사용한 반복, 추가, 제거
예제
import React, {useState} from 'react'; const IterationSample = () => { const [names, setNames] = useState([ {id: 0, text: '민지'}, {id: 1, text: '혜린'}, {id: 2, text: '하니'}, {id: 3, text: '다니'}, {id: 4, text: '혜인'}, ]); const [inputText, setInputText] = useState(''); const [nextId, setNextId] = useState(names.length); const onChange = e => setInputText(e.target.value); const onClick = () => { const newName = names.concat({ id: nextId, text: inputText }); setNextId(nextId + 1); setNames(newName); setInputText(''); }; const onDoubleClick = id => { const newNameList = names.filter(item => item.id !== id); setNames(newNameList); }; const nameList = names.map((item) => <li key={item.id} onDoubleClick={() => onDoubleClick(item.id)}>{item.text}</li> ); return ( <div> <input value={inputText} onChange={onChange}/> <button onClick={onClick}>추가</button> <ul>{nameList}</ul> </div> ); }; export default IterationSample;
답변
1. React에서 반복문을 사용하는 방법
- Map 을 사용하여 반복
'> Frontend > React' 카테고리의 다른 글
TIL-2024.04.30 - React - 006. Hooks (0) 2024.05.01 TIL-2024.04.29 - React - 005. Life Cycle Method (0) 2024.04.30 TIL-2024.04.27 - React - 003. Event Handler (0) 2024.04.27 TIL-2024.04.26 - React - 002-1. 단방향 통신 (Props & Callback) (0) 2024.04.27 TIL-2024.04.25 - React - 002. Component, Props, State (0) 2024.04.27