라이브러리/MUI

[MUI] <Switch/> 컴포넌트 스타일링(너비, 높이, ...) 커스터마이징 예시 코드

순코딩 2025. 4. 25. 15:38

미리보기

 

코드

////////////////////////////// 사용 예시 //////////////////////////////
<StyledSwitch $width={100} $height={50} />



////////////////////////////// 스타일 컴포넌트 타입 //////////////////////////////
type StyledSwitchPropsType = {
  $width: number;
  $height: number;
};


////////////////////////////// 스타일 컴포넌트 정의 //////////////////////////////
const StyledSwitch = styled(Switch, { shouldForwardProp })<StyledSwitchPropsType>`
  && {
    width: ${({ $width }) => $width}px;
    height: ${({ $height }) => $height + $height * 0.15}px;
    padding: 0px;

    .MuiSwitch-switchBase {
      padding: 0px;
      margin: ${({ $height }) => $height * 0.075}px;
      transform: translateX(0);

      &.Mui-checked {
        transform: translateX(${(props) => props.$width / 2 - props.$width * 0.1}px);

        & + .MuiSwitch-track {
          opacity: 1;
        }
      }
    }

    .MuiSwitch-thumb {
      width: ${({ $width }) => $width / 2}px;
      height: ${({ $height }) => $height}px;
      box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2);
      background-color: ${({ theme }) => theme.palette.background.paper};
    }

    .MuiSwitch-track {
      border-radius: ${({ $width }) => $width / 3}px;
      opacity: 0.5;
    }
  }
`;