Next 페이지에 토글 버튼 구현 (react-switch 활용)

우디·2024년 3월 4일
0
post-thumbnail

안녕하세요:) 개발자 우디입니다! 아래 내용 관련하여 작업 중이신 분들께 도움이되길 바라며 글을 공유하니 참고 부탁드립니다😊
(이번에 벨로그로 이사오면서 예전 글을 옮겨적었습니다. 이 점 양해 부탁드립니다!)

작업 시점: 2022년 1월

배경

  • 토글 버튼이 필요해서 관련하여 찾아보는데, 토글이라고도 하고 스위치 라고도 부름.
  • 찾아보다가 react-switch 라이브러리 활용하기로 결정.

react-switch 관련 조사

  • 설명
    • A draggable toggle-switch component for React.
  • 특징
    • Draggable with the mouse or with a touch screen.
    • Customizable - Easy to customize size, color and more.
    • Accessible to visually impaired users and those who can't use a mouse.
    • Reasonable package size - <2.5 kB gzipped.
    • It Just Works - Sensible default styling. Uses inline styles, so no need to import a separate css file.
  • 설치
    • yarn add react-switch
  • 사용법
    import React, { Component } from "react";
    import Switch from "react-switch";
    
    class SwitchExample extends Component {
      constructor() {
        super();
        this.state = { checked: false };
        this.handleChange = this.handleChange.bind(this);
      }
    
      handleChange(checked) {
        this.setState({ checked });
      }
    
      render() {
        return (
          <label>
            <span>Switch with default style</span>
            <Switch onChange={this.handleChange} checked={this.state.checked} />
          </label>
        );
      }
    }
  • API

실제 코드에 적용

  • 설치
    // package.json
    "react-switch": "^6.0.0",
  • 토글 버튼 구현
    import { useState, useEffect } from 'react';
    import Switch from 'react-switch';
    ...
    export default function Index({ id }) {
    const [autoPlayChecked, setAutoPlayChecked] = useState(true);
    const [autoPlayShown, setAutoPlayShown] = useState(false);
    ...
      <AutoPlayButtonWrapper style={{ display: autoPlayShown ? 'flex' : 'none' }}>
        <AutoPlayButtonText>Auto Play</AutoPlayButtonText>
        <AutoPlayButton
        onChange={() => {
          setAutoPlayChecked(!autoPlayChecked);
        }}
        checked={autoPlayChecked}
        />
    </AutoPlayButtonWrapper>
    • autoPlayChecked 에 따라 체크 되었는지 판단
    • autoPlayShown에 따라 사용자에게 보이는지 판단
profile
넓고 깊은 지식을 보유한 개발자를 꿈꾸고 있습니다:) 기억 혹은 공유하고 싶은 내용들을 기록하는 공간입니다

0개의 댓글