본문 바로가기

코딩도 합니다/React

[리액트 React] 리액트에서 체크박스 모양 변경하기(버튼) / 리액트에서 체크 박스 하나만 선택되게 하기 / How to change the appearance of a checkbox in react / How to make only one checkbox selected in react(button)



 

 

안녕하세요.

디자인도 하고, 개발도 하는 '디발자 뚝딱'입니다.

 

이번 포스팅에서는 아래 2가지를 중점적으로 다뤄보겠습니다.

1. 리액트에서 체크박스 모양 변경하기

2. 리액트에서 체크 박스 하나만 선택되게 하기

 

 

  1. 자, 먼저 jsx를 만들어 볼게요.

프로젝트 디렉터리 안에 CheckBox.js 를 만들어 주세요.

** 리액트 jsx에서는 label에 htmlFor를 사용합니다.

for는 js에서 반복문을 의미하는 키워드로, 중복되지 않기 위함입니다.

그냥 for를 사용할 경우 에러가 발생할 수 있으니 주의해 주세요!

// CheckBox.js

import React from 'react';

const CheckBoxTest = () => {
    return (
        <>
            <input type="checkbox" id="btn1" name="checkWrap" value="디자인" />
            <label htmlFor="btn1">디자인</label>
            <input type="checkbox" id="btn2" name="checkWrap" value="개발" />
            <label htmlFor="btn2">디자인</label>
            <input type="checkbox" id="btn3" name="checkWrap" value="뚝딱" />
            <label htmlFor="btn3">디자인</label>
        </>
    )
}

export default CheckBoxTest;

 

 

 

  2. 체크된 value를 가져오기 위해 state를만들고, 기능을 구현합니다.

리액트 hooks인 useState를 import한 다음에 state를 정의해 주세요.

그리고 state에 value를 담고,

useEffect로 state가 바뀔 때마다 console.log로 가져온 value를 확인합니다.

// CheckBox.js

import React, {useState, useEffect} from 'react';

const CheckBoxTest = () => {
	// checkbox value
    const [ checkValue, setCheckValue ] = useState('');
    
    function checkOnlyOne(id) {
        console.log('id', id);
        let checkPick = document.getElementsByName('checkWrap');
        Array.prototype.forEach.call(checkPick, function (el) {
          console.log('el', el);
          el.checked = false;
        });
        id.target.checked = true;
        setCheckValue(id.target.defaultValue);
    }
    
    useEffect(() => {
        // 선택한 value 확인하기
        console.log("체크박스 value", checkValue);
    }, [checkValue])

    return (
        <>
            <input 
            	type="checkbox" 
                id="btn1" 
                name="checkWrap" ㅁ
                value="디자인"
                onChange={(e) => checkOnlyOne(e)} 
            />
            <label htmlFor="btn1">디자인</label>
            
            <input 
            	type="checkbox" 
                id="btn2" 
                name="checkWrap" 
                value="개발"
                onChange={(e) => checkOnlyOne(e)} 
            />
            <label htmlFor="btn2">개발</label>
            
            <input 
            	type="checkbox" 
                id="btn3" 
                name="checkWrap"
                value="뚝딱"
                onChange={(e) => checkOnlyOne(e)}
            />
            <label htmlFor="btn3">뚝딱</label>
        </>
    )
}

export default CheckBoxTest;

 

 

 

  check박스를 버튼처럼 보이게 하기 위해서 style을 지정해줄게요.

먼저 터미널을 열어 아래의 명령어를 입력하여 styled-components 라는 리액트 라이브러리를 설치합니다.

npm i styled-components

 

styled-components를 설치했다면,

프로젝트 디렉터리 안에 CheckBox.styles.js 파일을 생성해주고 아래의 코드를 입력해 주세요.

// checkBox.styles.js
import styled from 'styled-components';

const CheckBoxCnt = styled.div`
    input[type=checkbox] {
        display: none;
    }

    input[type=checkbox] + label {
        flex:1;
        display: inline-block;
        margin: -2px;
        font: 0.8rem 'Noto Sans KR';
        text-align: center;
        background: #f5f6f7;
        border: 1px solid #ddd;
        padding: 6px 11px;
        box-sizing: border-box;
        cursor: pointer;
    }

    input[type=checkbox]:checked + label {
        background-image: none;
        background: #f3fbff;
        border: 1px solid #76d5ff;
        padding: 6px 11px;
        box-sizing: border-box;
        cursor: pointer;
        z-index: 1;
    }
`

export default CheckBoxCnt;

 

그리고 checkBox.js를 수정해 주세요.

// CheckBox.js
import React, {useState, useEffect} from 'react';
import CheckBoxCnt from './CheckBox.styles';

const CheckBoxTest = () => {
	// checkbox value
    const [ checkValue, setCheckValue ] = useState('');
    
    function checkOnlyOne(id) {
        console.log('id', id);
        let checkPick = document.getElementsByName('checkWrap');
        Array.prototype.forEach.call(checkPick, function (el) {
          console.log('el', el);
          el.checked = false;
        });
        id.target.checked = true;
        setCheckValue(id.target.defaultValue);
       
    }
    
    useEffect(() => {
        // 선택한 value 확인하기
        console.log("체크박스 value", checkValue);
    }, [checkValue])

    return (
        <checkBoxCnt>
            <input 
            	type="checkbox" 
                id="btn1" 
                name="checkWrap" ㅁ
                value="디자인"
                onChange={(e) => checkOnlyOne(e)} 
            />
            <label htmlFor="btn1">디자인</label>
            
            <input 
            	type="checkbox" 
                id="btn2" 
                name="checkWrap" 
                value="개발"
                onChange={(e) => checkOnlyOne(e)} 
            />
            <label htmlFor="btn2">개발</label>
            
            <input 
            	type="checkbox" 
                id="btn3" 
                name="checkWrap"
                value="뚝딱"
                onChange={(e) => checkOnlyOne(e)}
            />
            <label htmlFor="btn3">뚝딱</label>
        </checkBoxCnt>
    )
}

export default CheckBoxTest;

 

 

  완성된 화면

체크박스가 버튼 모양으로 바뀌고,

하나를 선택하면 나머지 체크박스가 해제되는 것을 확인할 수 있습니다.

 

 

 

 

728x90