728x90
반응형
기능 요약
리액트 체크박스 선택 기능
출처 : https://www.freecodecamp.org/news/how-to-work-with-multiple-checkboxes-in-react/
설명
allChecked = 모두 선택하는 체크박스
checkedState = 일반 체크박스
const [isAllChecked, setAllChecked] = useState(false);
const [checkedState, setCheckedState] = useState(new Array(2).fill(false));
const handleAllCheck = () => {
setAllChecked((prev) => !prev);
let array = new Array(2).fill(!isAllChecked);
setCheckedState(array);
};
const handleMonoCheck = (position: number) => {
const updatedCheckedState = checkedState.map((item, index) =>
index === position ? !item : item
);
setCheckedState(updatedCheckedState);
const checkedLength = updatedCheckedState.reduce((sum, currentState) => {
if (currentState === true) {
return sum + 1;
}
return sum;
}, 0);
setAllChecked(checkedLength === updatedCheckedState.length);
};
전체 체크와 일반 체크박스
<div>
<input
type="checkbox"
checked={isAllChecked}
onChange={() => handleAllCheck()}
/>
all check
</div>
<div>
<input
type="checkbox"
checked={checkedState[0]}
onChange={() => handleMonoCheck(0)}
/>
check 0
</div>
<div>
<input
type="checkbox"
checked={checkedState[1]}
onChange={() => handleMonoCheck(1)}
/>
check 1
</div>
codesandbox 미리보기
반응형
'Dev > Frontend' 카테고리의 다른 글
React Router 리액트 라우터 용어해설(URL, Location, Location State, History Stack, CSR, History, Segment, Path Pattern, Dynamic Segment) (0) | 2022.08.25 |
---|---|
[jsp] 1000단위 구분기호 넣기 (0) | 2022.08.23 |
React typescript로 초기 프로젝트 설정하기. + 기본 라이브러리 (0) | 2022.07.30 |
리액트의 Hydration의 이해 (0) | 2022.07.30 |
아코디언 1개만 열리는 예제 (0) | 2020.01.23 |