React

[React-Native] BottomSheet 사용하기

개발조무사 윤뚜비 2023. 1. 2. 22:10

 

바텀시트란

 

이 처럼 바닥에서 위로 올라오는 화면을 바텀시트(Bottom Sheet)라고 한다.

본 글에서는 바텀시트를 구현하기위해 라이브러리를 사용할 것이다.

 

 

 

라이브러리 설치

 

먼저 아래 라이브러리를 설치해주자.

yarn add @gorhom/bottom-sheet@^4 

gorhom.github.io 공식 홈페이지

 

공식문서에 따르면 아래 종속된 패키지도 설치해야 한다고 한다.

 

yarn add react-native-reanimated react-native-gesture-handler

 

 

 

 

 

이후 babel.config.js파일에 플러그인 맨 뒤에 추가해 준다.

 

 

 

이제 아래 두 태그를 최상단에 넣고 내부에 바텀시트를 선언해주고 사용해주면 된다.

 

 

 

 

 

공식문서의 예제에 뒤에 오버레이 스크린의 순서만 살짝 바꿔 자연스럽게 만들어준 코드는 아래와 같다.

 

import React, { useCallback, useMemo, useRef } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import BottomSheet from '@gorhom/bottom-sheet';

const App = () => {
  // ref
  const bottomSheetRef = useRef<BottomSheet>(null);

  // variables
  const snapPoints = useMemo(() => ['25%', '50%'], []);

  // callbacks
  const handleSheetChanges = useCallback((index: number) => {
    console.log('handleSheetChanges', index);
  }, []);

  // renders
  return (
    <View style={styles.container}>
      <BottomSheet
        ref={bottomSheetRef}
        index={1}
        appearsOnIndex={0}
    	disappearsOnIndex={-1}
        snapPoints={snapPoints}
        onChange={handleSheetChanges}
      >
        <View style={styles.contentContainer}>
          <Text>Awesome 🎉</Text>
        </View>
      </BottomSheet>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 24,
    backgroundColor: 'grey',
  },
  contentContainer: {
    flex: 1,
    alignItems: 'center',
  },
});

export default App;

 

참고

 

또, 바텀시트 내부에서 스크롤을 이용하려면

@gorhom/bottom-sheet 패키지 내부의 BottomSheetScrollView로 감싸주도록 하자.

 

아래 보일러플레이트 코드를 참고하면 이해하기 쉽다.

https://github.com/consolekakao/reactnative-boilerplate/commit/b80b40834b1b0b986942d256b3ea17b1cc2a547d