[React + Typescript + emotion] Toggle 컴포넌트 제작

2024. 8. 8. 16:46

마이페이지에서 옵션을 켜고 끌 수 있는 토글을 만들었었다.

 

몰랐는데 type="checkbox"로 했던 게 신기했던!

아직 토글을 켜고, 끌 때의 기능은 개발이 안되어서 toast를 띄우는 것으로만 구현되었다.

 

// Toggle.tsx
import { useState } from "react";
import * as S from "./Toggle.styled";
import { useToast } from "hooks";

interface ToggleProps {
  content?: string;
}

const Toggle = ({ content }: ToggleProps) => {
  const [isToggleOn, setIsToggleOn] = useState<boolean>(false);
  const { addToast } = useToast();

  const handleToggle = () => {
    const newToggleState = !isToggleOn;
    setIsToggleOn(newToggleState);

    if (newToggleState) {
      addToast({ content: content });
    }
  };

  return (
    <S.Toggle checked={isToggleOn}>
      <S.Checkbox id="toggle" type="checkbox" onChange={handleToggle} />
    </S.Toggle>
  );
};

export default Toggle;

 

 

css에선 input의 체크박스를 가려줘야 하는 css도 필요하다.

// Toggle.styled.ts
import { css } from "@emotion/react";
import styled from "@emotion/styled";

export const Toggle = styled.label<{ checked: boolean }>`
${({ checked, theme }) => css`
display: inline-block;
cursor: pointer;
width: 44px; 
height: 26px; 
background: ${checked ? theme.colors.pink900 : theme.colors.gray600}; 
border-radius: 14px ;
position: relative;

&:after {
  content: "";
  position: absolute;
  left: ${checked ? "calc(44.5%)" : "calc(5.5%)"};
  top: 2px; 
  width: 22px; 
  height: 22px; 
  background: #fff;
  border-radius: 50%;
  transition: 0.3s;

`}
  }
`;

export const Checkbox = styled.input`
  visibility: hidden;
`;

 

어렵게 생각했었는데 검색의 도움이 필요하긴 했지만 그래도 생각보다 간단했던 토글이었다.

BELATED ARTICLES

more