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

React Native에서 머티리얼 칩(Material Chip) 표시하는 방법

앱 UI에 칩(Chip)을 표시하려면 React Native Paper가 제공하는 머티리얼 디자인 컴포넌트를 활용하면 됩니다. React Native Paper는 구글의 머티리얼 디자인 가이드라인을 따르는 대표적인 UI 라이브러리로, 칩 외에도 버튼, 카드, 다이얼로그 등 다양한 컴포넌트를 손쉽게 사용할 수 있습니다.

react-native-paper 설치하기

아래 명령어를 실행해 react-native-paper를 프로젝트에 설치합니다.

npm install --save-dev react-native-paper

칩(Chip) 컴포넌트란?

칩은 태그, 필터 조건, 선택 항목 등을 간결하게 표현할 때 유용한 UI 요소입니다. React Native Paper의 칩 컴포넌트는 화면에서 다음과 같이 표시됩니다.

React Native에서 머티리얼 칩(Material Chip) 표시하는 방법

기본 문법

<Chip icon="icontodisplay" onPress={onPressfunc}>Chip Name</Chip>

칩의 주요 속성(Props)

칩 컴포넌트에서 자주 사용되는 기본 속성은 다음과 같습니다.

속성설명
modeflatoutlined 두 가지 값을 사용할 수 있습니다. flat 모드는 테두리가 없고, outlined 모드는 칩 주위에 테두리가 표시됩니다.
icon칩에 표시할 아이콘을 지정합니다.
selectedtrue/false 값을 가지며, true일 경우 칩이 선택된 상태로 표시됩니다.
selectedColor선택된 칩에 적용할 색상을 지정합니다.
disabled칩을 비활성화하여 사용자 입력을 차단합니다.
onPress사용자가 칩을 탭했을 때 호출되는 함수입니다.
onClose사용자가 닫기 버튼을 탭했을 때 호출되는 함수입니다.
textStyle칩 내부 텍스트에 적용할 스타일입니다.
style칩 컴포넌트 자체에 적용할 스타일입니다.

예제 1: 칩 표시하기

칩을 화면에 표시하는 기본적인 코드는 다음과 같습니다.

<SafeAreaView style={styles.container}>
    <Chip icon="camera" disabled onPress={() => console.log('camera')}>Click Here</Chip>
    <Chip icon="apple" mode="outlined" selectedColor='green' selected
        onPress={() => console.log('apple')}>Apple Icon</Chip>
</SafeAreaView>

예제 2: 전체 코드

세 가지 칩(비활성화 칩, 선택된 칩, 날짜 선택 칩)을 함께 구성한 전체 예제입니다.

import * as React from 'react';
import { StyleSheet, Text, SafeAreaView } from 'react-native';
import { Chip } from 'react-native-paper';

const MyComponent = () => (
    <SafeAreaView style={styles.container}>
        <Chip icon="camera" style={styles.chip} disabled onPress={() =>
            console.log('camera')}>Click Here</Chip>
        <Chip icon="apple" style={styles.chip}
            mode="outlined" selectedColor='green' selected onPress={() =>
            console.log('apple')}>Apple Icon</Chip>
        <Chip icon="calendar-month" style={styles.chip} mode="outlined" selected
            onPress={() => console.log('calendar')}>Select Date</Chip>
    </SafeAreaView>
);

export default MyComponent;

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

실행 결과

위 코드를 실행하면 비활성화된 카메라 칩, 초록색으로 강조된 Apple 칩, 그리고 날짜 선택 칩이 화면 중앙에 세로로 배치되어 표시됩니다.

React Native에서 머티리얼 칩(Material Chip) 표시하는 방법

마무리

React Native Paper의 Chip 컴포넌트를 활용하면 복잡한 스타일링 없이도 머티리얼 디자인 규격에 맞는 칩 UI를 빠르게 구현할 수 있습니다. mode, selected, selectedColor 등의 속성을 조합하면 필터, 태그 선택, 옵션 입력 등 다양한 인터랙션을 손쉽게 만들 수 있으니, 실제 프로젝트에 적용해 보시기 바랍니다.