728x90
반응형
Ex.01. HTML을 사용한 list출력
const IterationSample = () => {
return (
<ul>
<li>눈사람</li>
<li>호빵</li>
<li>눈</li>
<li>바람</li>
</ul>
)
}
export default IterationSample;
Ex02. map을 이용한 list 출력
보다 간편한 출력이 가능하다.
const IterationSample = () => {
const names = ['눈사람', '호빵', '눈', '바람'];
const nameList = names.map((name)=><li>{name}</li>);
return (
<ul>
{nameList}
</ul>
)
}
export default IterationSample;
Ex03. Concat을 사용한 list추가
import { 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,
text:inputText
})
setNextId(nextId+1);
setNames(nextNames);
setInputText("");
}
const nameList = names.map((name)=>(
<li key={name.id}>{name.text}</li>
))
return (
<>
<input value={inputText} onChange={onChange} />
<button onClick={onClick}>추가</button>
<ul>{nameList}</ul>
</>
)
}
export default IterationSample;
Ex04. filter을 사용한 list 삭제
li를 더블 클릭하면 삭제됨
import { 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,
text:inputText
})
setNextId(nextId+1);
setNames(nextNames);
setInputText("");
}
const onRemove=(id)=>{
const nextNames = names.filter((name)=>name.id !== id);
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;
728x90
반응형
'Front-End > REACT' 카테고리의 다른 글
[REACT] 라이브러리 (0) | 2022.12.09 |
---|---|
[REACT/JavaScript] map() (0) | 2022.12.08 |
[REACT] input 클릭이벤트 (0) | 2022.12.07 |
[VSCode] 유용한 확장프로그램 (0) | 2022.12.05 |
[REACT] CMD를 이용해 REACT 개발환경을 설치하는 2가지 방법 - npm과 yarn (0) | 2022.12.05 |
댓글