console.clear();
import React, { useState } from "https://cdn.skypack.dev/react@18";
import ReactDOM from "https://cdn.skypack.dev/react-dom@18";
const App = () => {
const fruits = ["사과", "바나나", "귤"];
const [selecteds, setSelecteds] = useState(
new Array(fruits.length).fill(false)
);
const toggleFruitSelected = (index) => {
const newSelecteds = selecteds.map((el,_index) => _index == index ? !el : el);
setSelecteds(newSelecteds);
}
const selectedFruits = selecteds.map((el,index) => (el ? fruits[index] : el)).filter((el) => el);
return (
<>
<h4 className="font-bold">체크박스 연습</h4>
<ul>
{fruits.map((fruit, index) => (
<li key={index}>
<label className="cursor-pointer flex items-center gap-x-3">
<input type="checkbox" value={fruit} className="checkbox checkbox-primary" onChange={() => toggleFruitSelected(index)}/>
<span>{fruit}</span>
</label>
</li>
))}
</ul>
<hr/>
<div>select status : {JSON.stringify(selecteds)}</div>
<div>select fruit : {selectedFruits.join(', ')}</div>
</>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
- .fill() : useState 초기화될 때 채움
- .join() : 배열의 원소를 문자열로 합치기
'JavaScript > React' 카테고리의 다른 글
React - Recoil(React 상태 관리 라이브러리) (1) | 2024.04.05 |
---|---|
React - MUI 라이브러리, forwardRef (0) | 2024.04.05 |
React - css변수 (0) | 2024.04.03 |
React - 음식 주문 폼 (0) | 2024.04.01 |
React - 할 일 폼 만들기(6)_삭제, 수정, 커스텀 Hook (0) | 2024.03.30 |