커스텀 라디오 버튼

gusdas·2022년 5월 12일
0

에러노트

목록 보기
10/22

어려운 방법

직접 구현했는데 더 쉬운 방법이 있었다.

쉬운방법

input 태그에 display: none을 주고 label클릭시 useState로 변경

const [check, setCheck] = React.useState('content1');
  const handleChkChange = (e) => {
    setCheck(e.target.id);
  };
<Radio
  onChange={handleChkChange}
  id="content1"
  type="radio"
  name="share"></Radio>
<Label check={check === 'content1'} htmlFor="content1">
  나눔해요
</Label>
const Radio = styled.input`
  display: none;
  margin-right: 1rem;
`;

const Label = styled.label`
  height: 48px;
  width: 44vw;
  display: inline-block;
  background-color: lightgray;
  display: flex;
  justify-content: center;
  align-items: center;
  ${(props) => (props.check ? 'background-color:  #5C5C5C; color:white;' : '')}
`;

전체코드

import React from 'react';
import styled from 'styled-components';



function EditParty() {
 
  const [check, setCheck] = React.useState('content1');
  const handleChkChange = (e) => {
    setCheck(e.target.id);
  };

  return (
    <>
      <FlexDiv>
        <div>
          <Radio
            onChange={handleChkChange}
            id="content1"
            type="radio"
            name="share"></Radio>
          <Label check={check === 'content1'} htmlFor="content1">
            나눔해요
          </Label>
        </div>
        <div>
          <Radio
            onChange={handleChkChange}
            id="content2"
            type="radio"
            name="share"></Radio>
          <Label check={check === 'content2'} htmlFor="content2">
            나눔해줘요
          </Label>
        </div>
      </FlexDiv>
 
    </>
  );
}

const FlexDiv = styled.div`
  display: flex;
  width: 100%;
  div:first-child {
    margin-right: 0.5rem;
  }
`;
const Radio = styled.input`
  display: none;
  margin-right: 1rem;
`;
const Label = styled.label`
  height: 48px;
  width: 44vw;
  display: inline-block;
  background-color: lightgray;
  display: flex;
  justify-content: center;
  align-items: center;
  ${(props) => (props.check ? 'background-color:  #5C5C5C; color:white;' : '')}
`;


export default EditParty;
profile
웹개발자가 되자

0개의 댓글