Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

React Native SwitchSelector 컴포넌트 완벽 가이드 – 설치부터 주요 속성과 실전 예제까지

SwitchSelector 컴포넌트란?

React Native의 SwitchSelector 컴포넌트는 라디오 토글 버튼과 유사한 UI 요소로, 두 개 이상의 값을 선택할 수 있도록 해주는 위젯입니다. 일반적인 스위치(Switch)가 ON/OFF처럼 두 가지 상태만 표현하는 것과 달리, SwitchSelector는 여러 개의 옵션 중 하나를 직관적으로 고를 수 있어 성별 선택, 카테고리 필터, 정렬 기준 선택 등 다양한 상황에서 유용하게 활용됩니다.

패키지 설치

SwitchSelector를 사용하려면 먼저 아래 명령어로 패키지를 설치해야 합니다.

npm i react-native-switch-selector --save-dev

설치 후 가장 기본적인 형태의 SwitchSelector는 다음과 같이 작성합니다.

<SwitchSelector
    options={youroptions}
    initial={0}
    onPress={value => console.log(`선택된 값 : ${value}`)}
/>

SwitchSelector의 주요 속성(Props)

SwitchSelector를 효과적으로 사용하려면 아래 표의 주요 속성들을 이해하고 있어야 합니다.

속성설명
options라벨(label), 값(value), 이미지 아이콘(imageIcon)을 포함하는 배열로, 필수 항목입니다.
initial배열에서 화면 로딩 시 처음 선택되어 있을 항목의 인덱스입니다.
valueonPress 이벤트 발생 시 함께 전달되는 스위치의 값입니다.
onPress스위치 선택이 변경될 때 호출되는 콜백 함수를 등록하는 이벤트입니다.
fontSize라벨 텍스트에 적용할 글자 크기입니다.
selectedColor선택된 항목의 텍스트 색상입니다.
buttonColor선택된 항목의 배경색입니다.
textColor선택되지 않은 항목의 라벨 색상입니다.
backgroundColor스위치 셀렉터 컴포넌트 전체의 배경색입니다.
borderColor컴포넌트 외곽에 지정할 테두리 색상입니다.

예제 1: 남성/여성 선택 SwitchSelector 만들기

SwitchSelector를 사용하려면 먼저 컴포넌트를 임포트해야 합니다.

import SwitchSelector from "react-native-switch-selector";

이번 예제에서는 여성(Female) / 남성(Male) 두 가지 옵션을 표시해 보겠습니다. 각 옵션에는 이미지 아이콘을 함께 사용하며, 이미지는 options 배열에 담아 전달합니다.

let male = require('C:/myfirstapp/myfirstapp/assets/male.png');
let female = require('C:/myfirstapp/myfirstapp/assets/female.png');
const images = {
    "female": female,
    "male": male,
};
const options = [
    { label: "Female", value: "f", imageIcon: images.female },
    { label: "Male", value: "m", imageIcon: images.male }
];

이렇게 준비한 옵션 배열을 SwitchSelector에 적용하면 다음과 같습니다.

<SwitchSelector
    initial={0}
    onPress={value => this.setState({ gender: value })}
    textColor='#ccceeaa'
    selectedColor='#7a44cf'
    buttonColor='#ccc'
    borderColor='#ccc'
    hasPadding
    options={options}
/>

전체 소스 코드

import React, { Component } from 'react';
import { StyleSheet, SafeAreaView } from 'react-native';
import SwitchSelector from "react-native-switch-selector";

let male = require('C:/myfirstapp/myfirstapp/assets/male.png');
let female = require('C:/myfirstapp/myfirstapp/assets/female.png');

const images = {
    "female": female,
    "male": male,
};

const options = [
    { label: "Female", value: "f", imageIcon: images.female },
    { label: "Male", value: "m", imageIcon: images.male }
];

export default class MySwitchSelectorComponent extends Component {
    render() {
        return (
            <SafeAreaView style={styles.container}>
                <SwitchSelector
                    initial={0}
                    onPress={value => this.setState({ gender: value })}
                    textColor='#ccceeaa'
                    selectedColor='#7a44cf'
                    buttonColor='#ccc'
                    borderColor='#ccc'
                    hasPadding
                    options={options}
                />
            </SafeAreaView>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: "center",
        justifyContent: "center"
    },
});

실행 결과

위 코드를 실행하면 여성/남성 두 옵션이 나란히 배치된 토글 형태의 선택 UI가 화면 중앙에 표시됩니다. 옵션을 누르면 해당 값이 state의 gender 값으로 저장됩니다.

React Native SwitchSelector 컴포넌트 완벽 가이드 – 설치부터 주요 속성과 실전 예제까지

예제 2: 세 개의 옵션을 가진 SwitchSelector

SwitchSelector는 두 개뿐만 아니라 세 개 이상의 옵션도 손쉽게 처리할 수 있습니다. 아래 예제에서는 First, Second, Third 세 가지 옵션을 사용합니다.

const options = [
    { label: "First", value: "a" },
    { label: "Second", value: "b" },
    { label: "Third", value: "c" }
];

전체 소스 코드

import React, { Component } from 'react';
import { StyleSheet, SafeAreaView } from 'react-native';
import SwitchSelector from "react-native-switch-selector";

const options = [
    { label: "First", value: "a" },
    { label: "Second", value: "b" },
    { label: "Third", value: "c" }
];

export default class MySwitchSelectorComponent extends Component {
    render() {
        return (
            <SafeAreaView style={styles.container}>
                <SwitchSelector
                    initial={0}
                    onPress={value => this.setState({ gender: value })}
                    textColor='#ccceeaa'
                    selectedColor='#7a44cf'
                    buttonColor='#ccc'
                    borderColor='#ccc'
                    fontSize='30'
                    hasPadding
                    options={options}
                />
            </SafeAreaView>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    }
});

실행 결과

실행하면 세 개의 옵션이 균등하게 분할된 토글 버튼이 표시되며, fontSize 속성 덕분에 라벨 글자 크기가 커진 것을 확인할 수 있습니다.

React Native SwitchSelector 컴포넌트 완벽 가이드 – 설치부터 주요 속성과 실전 예제까지

마무리

SwitchSelector는 설치와 설정이 간단하면서도 라디오 버튼보다 세련된 UX를 제공하는 컴포넌트입니다. options 배열에 원하는 만큼 항목을 추가하기만 하면 되므로, 설정 화면이나 필터 UI 등에서 두 개 이상의 선택지를 깔끔하게 처리해야 할 때 적극적으로 활용해 보시기 바랍니다.