본문 바로가기
I can do it on my own!/리액트

[React] Toggle Button 구현하기

by zivvon 2022. 1. 29.
목차 접기

; 리액트에서 토글버튼 구현하기

 

1. CustomSwitch.js : 토글버튼을 디자인할 js를 생성한다.

import React, { useState } from 'react';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native'

const CustomSwitch = ({
    navigation,
    selectionMode,
    roundCorner,
    option1, //토글버튼에 쓰여질 text1
    option2, //토글버튼에 쓰여질 text2
    onSelectSwitch,
    selectionColor
  }) => {
    const [getSelectionMode, setSelectionMode] = useState(selectionMode);
    const [getRoundCorner, setRoundCorner] = useState(roundCorner);
  
    const updatedSwitchData = val => {
      setSelectionMode(val);
      onSelectSwitch(val);
    };
  
    return (
      <View>
        <View
        //각자 원하는 모양에 따라 디자인
          style={{
            height: 42,
            width: 145,
            backgroundColor: '#1E2A35',
            borderRadius: getRoundCorner ? 25 : 0,
            borderWidth: 1,
            borderColor: '#1E2A35',
            flexDirection: 'row',
            justifyContent: 'center',
            padding: 2,
            color: '#B4B6B8',
          }}>
            <TouchableOpacity
              activeOpacity={1}
              onPress={() => updatedSwitchData(1)}
              style={{
                flex: 1,
                backgroundColor: getSelectionMode === 1 ? selectionColor : '#1E2A35',
                borderRadius: getRoundCorner ? 25 : 0,
                justifyContent: 'center',
                alignItems: 'center',
              }}>
              <Text
                style={{
                  color: getSelectionMode === 1 ? 'white' : selectionColor,
                }}>
                  {option1}
                </Text>
                </TouchableOpacity>
                <TouchableOpacity
                  TouchableOpacity 
                  activeOpacity={1}
                  onPress={() => updatedSwitchData(2)}
                  style={{
                    flex: 1,
                    backgroundColor: getSelectionMode === 2 ? selectionColor : '#1E2A35',
                    borderRadius: getRoundCorner ? 25 : 0,
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}>
                    <Text
                      style={{
                        fontColor: '#B4B6B8',
                        color: getSelectionMode === 2 ? 'white' : selectionColor,
                      }}>
                        {option2}
                      </Text>
                  </TouchableOpacity>
          </View>
      </View>
    );
  };

  export default CustomSwitch;

토글버튼 상 왼쪽 버튼, 오른쪽 버튼으로 나누어 생각하면 된다.

 

2. ToggleButton.js : 디자인한 토글버튼을 실제 보여질 토글버튼으로 만드는 js를 생성한다.

import React from 'react';
import { View } from 'react-native'
import CustomSwitch from './CustomSwitch';

//토글 스위치 Dashboard screen
export default function Dashboard({navigation}){
    const onSelectSwitch = index => {
      //토글버튼 상 왼쪽 버튼 index 1, 오른쪽 버튼 index 2
      //각자 개발 환경에 맞게 index를 사용하면 될 것 같다.
    };
  
    return (
      <View style={{alignItems: 'center'}}>
        <View style={{alignItems: 'center', marginBottom: 60}}>
          <CustomSwitch
            selectionMode={1}
            roundCorner={true}
            option1={'1'}
            option2={'2'}
            onSelectSwitch={onSelectSwitch}
            selectionColor={'#374756'}
          />
        </View>
      </View>
    );
  }

위에서 만들었던 CustomSwitch.js의 컴포넌트를 호출해주면 된다.

 

3. 결과!

토글버튼을 클릭할 때 alert 창이 뜨게 구현해서 매끄럽지 않아 보인다.

alert 창 없애면 버튼이 부드럽게 넘어가는 것을 확인할 수 있다!

 

 


 

https://www.techup.co.in/custom-toggle-switch-in-react-native/

리액트 토글버튼에 대해 여기저기 서치해보면서 위 페이지가 가장 자세하다고 느꼈다.

참고해서 공부하면 좋을 듯 싶다!

'I can do it on my own! > 리액트' 카테고리의 다른 글

[React] 현재 날짜 값 받아오기  (0) 2022.01.29
Ch1. 리액트 시작  (0) 2022.01.21