본문 바로가기

카테고리 없음

[React] 애니메이션이 포함된 간단한 toggle 버튼 만들기 (make a toggle button using just react)

토글에 애니메이션을 넣어 동작시켜보았다. 이렇게 만들게 되면 따로 토글 버튼 모듈을 추가하지 않고도 간단하게 토글을 생성할 수 있으며, 다양한 애니메이션이나 옵션을 추가하여 사용할 수 있다.

먼저 토글을 동작 시킬 parent div에 onClick 함수로 토글 형식을 넣어주고, 

toggle시 동작시킬 container와 circle의 클릭시 부여되는 css className을 각각 부여해준다.

 

I generate a toggle button with simple animation. This Component is very useful to create and custom a new toggle button. You can use it with adding some other custom options. 

First of all you need an onClick Function inside the parend <div>.

And create css class names which can active the toggle like 'toggle--checked'

import React, { useState } from "react";
const ToggleBtn = () => {
  const [isOn, setisOn] = useState(false);

  const toggleHandler = () => {
    setisOn(!isOn);
  };

  return (
    
    <>
      <div className="toggle" onClick={toggleHandler}>
        <div className={`toggle-container ${isOn ? "toggle--checked" : ""}`} />
        <div className={`toggle-circle ${isOn ? "toggle--checked" : ""}`} />
      </div>
    </>
  );
};

export default ToggleBtn;

parent div에 relative 포지션을 부여하고 움직이게 될 child div 인 toggle-circle에 absolute로 초기값 지정을 하고,

action이 가해지면 (toggle--checked) 해당 toggle-circle의 위치를 변동, 혹은 background에 해당되는 toggle-container의 애니메이션을 변경시킬 수 있다.

Make a position:relative  in parent <div> and position:absolute in children <div> named 'toggle-circle' which you make it in the css file. If you do some actions, you can chage the background or the distance using 'toggle--checked' that you create before.

//css파일
.toggle {
  position: relative;
  cursor: pointer;
}

.toggle .toggle-container{
  width: 44px;
  height: 24px;
  border-radius: 30px;
  background-color: #d4d3d3;
  transition: all 0.2s ease;
}

.toggle .toggle-container.toggle--checked{
  background-color: #61BE82;
}

.toggle .toggle-circle{
  position: absolute;
  top: 4px;
  left: 4px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background-color: #fafafa;
  transition: all 0.25s ease;
}

.toggle .toggle-circle.toggle--checked{
  left: 24px;
}