Toggle button with styled-components

Darcy Daeseok YU ·2022년 2월 1일
0

토글 버튼을 그려봅니다.

구조는
Container
└ InnerContainer (position : relative )
└ ToggleCircle (position : absolute )
로 구성합니다.

transition 무빙 이펙트를 사용하기 위해서는 특정 css prop을 사용해야합니다.
예) dispaly : flex ; justify-content : flex-start
== > justify-content:flex-end (x) 는 transition이 동작하지 않습니다.

여기서는 left : 0px / right : 0px 을 사용합니다.
left : 0px
==> (circle ------)
right : 0px
==> (------ circle)

  1. Structure of tags
    구조는 간단합니다.
    <Container isTrue={isTrue} onClick={onToggleMode}>
       <InnerContainer isTrue={isTrue}>
         <TggleCircle>{isTrue ? <span>On</span> : <span>Off</span>}</TggleCircle>
       </InnerContainer>
     </Container>
2. css 정의 w/styled-components 
styled.div<{ isTrue: boolean }> 뒤에 `css 내용` 백팁 안에 css를 정의합니다. 
코드에 `백팁이 표시가 안되네요. 

const Container = styled.div<{ isTrue: boolean }> display: flex; align-items: center; justify-content: center; padding: 2px; width: 60px; height: 18px; background-color: ${(props) => (props.isTrue ? "white" : "black")}; border-radius: 20px; cursor: pointer;;
const InnerContainer = styled.div<{ isTrue: boolean }>`
transition: all 0.5s ease;
background-color: ${(props) =>
props.isTrue ? "rgba(255, 255, 255, 0.8)" : "rgba(255, 255, 255, 0.5)"};
width: 100%;
height: 18px;
border-radius: 17px;
position: relative;

div {
background-color: ${(props) =>
props.isTrue ? "rgba(0,0,0,0.8)" : "white"};
right: ${(props) => (props.isTrue ? "0px" : "28px")};
}
`;

const TggleCircle = styled.div transition: all 0.5s ease; position: absolute; width: 32px; height: 18px; font-size: 0.8rem; border-radius: 20px; display: flex; align-items: center; justify-content: center;;


위의 코드는 framer-motion을 사용하면 쉽게 이펙트를 구현할수 있습니다. 
profile
React, React-Native https://darcyu83.netlify.app/

0개의 댓글