-
React) iOS 스타일의 Switch 버튼 만들기카테고리 없음 2023. 3. 15. 21:42728x90반응형
Component 코드
import styles from '../../../styles/Swtich.module.css'; const Switch = ({ isOn, handleToggle }) => { // 랜덤 키를 생성하지 않으면 component로 분리하여 Switch를 객체화 하여도 input과 label의 아이디가 동일하여 // 객체화해서 따로사용할수가 없다. const rand = Math.floor(Math.random() * 100); const key = `${Date.now()}${rand}`; return ( <> <input checked={isOn} onChange={handleToggle} className={styles.react__switch__checkbox} id={`react-switch-new-${key}`} type="checkbox" /> <label style={{ background: isOn && '#4285F4' }} className={styles.react__switch__label} htmlFor={`react-switch-new-${key}`} > <span className={styles.react__switch__button} /> </label> </> ); }; export default Switch;
- CSS 코드
.react__switch__checkbox { height: 0; width: 0; visibility: hidden; } .react__switch__label { display: flex; align-items: center; justify-content: space-between; cursor: pointer; width: 60px; height: 30px; background: grey; border-radius: 30px; position: relative; transition: background-color .2s; } .react__switch__label .react__switch__button { content: ''; position: absolute; top: 2px; left: 2px; width: 26px; height: 26px; border-radius: calc(100% / 2); transition: 0.2s; background: #fff; box-shadow: 0 0 2px 0 rgba(10, 10, 10, 0.29); } .react__switch__checkbox:checked + .react__switch__label .react__switch__button { left: calc(100% - 2px); transform: translateX(-100%); } .react__switch__label:active .react__switch__button { width: 30px; }
참고 URL
https://upmostly.com/tutorials/build-a-react-switch-toggle-component
도움 되셨다면 하단의 광고 클릭 센스!!
728x90반응형