React, Iteration, 컴포넌트 배열로 반환하기, map
2024. 12. 16. 09:46ㆍ웹 개발
Iteration.jsx
import React, { useState } from "react";
import styled from "styled-components";
const ListItem = styled.li`
margin: 0;
padding: 5px 0;
user-select: none;
cursor: pointer;
transition: all 0.2s;
&:hover {
background-color: #eee;
}
`;
const IterationSample = () => {
const [names, setNames] = useState([
{ id: 1, text: "눈사람" },
{ id: 2, text: "얼음" },
{ id: 3, text: "눈" },
{ id: 4, text: "바람" },
{ id: 5, text: "비" },
]);
const [inputText, setInputText] = useState("");
const [nextId, setNextId] = useState(names.length + 1);
const onChange = (e) => setInputText(e.target.value);
const onClick = () => {
if (!inputText.trim()) return; // 빈 입력 방지
setNames([...names, { id: nextId, text: inputText }]);
setNextId(nextId + 1);
setInputText("");
};
const onRemove = (id) => setNames(names.filter((name) => name.id !== id));
return (
<>
<input type="text" value={inputText} onChange={onChange} />
<button onClick={onClick}>추가</button>
<ul>
{names.map(({ id, text }) => (
<ListItem key={id} onDoubleClick={() => onRemove(id)}>
{text}
</ListItem>
))}
</ul>
</>
);
};
export default IterationSample;
https://stackblitz.com/edit/react-basecamp-uatrwtws?embed=1&file=src%2FIteration.jsx
'웹 개발' 카테고리의 다른 글
React Playground / playcode.io (0) | 2024.12.18 |
---|---|
React, useMemo, useCallback (0) | 2024.12.16 |
React, ScrollBox, Ref, 참조 (0) | 2024.12.13 |
React, useState, Counter.js (0) | 2024.12.13 |
React, Vite + 리액트 프로젝트 시작하기 (1) | 2024.12.13 |