JavaScript/React

React - CheckBox

내이름효주 2024. 4. 5. 10:10
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() : 배열의 원소를 문자열로 합치기