React Native 앱 Drawer 구현하기 (react-native-gesture-handler)

React Native에서 Drawer를 구현하기 위해서 다양한 라이브러리가 있다.

그런데, React Navigation Stack 등에서 사용하기 위해 설치하는 react-native-gesture-handler에 Drawer에 대한 기능이 이미 구현되어 있다는 것을 최근에 알게 되었다.

이를 모르고, Drawer에 대한 라이브러리나 중복 구현을 하는 것을 막고자 이 글을 남기게 되었다.

 

 react-native-gesture-handler는 DrawerLayout 이라는 컴포넌트를 가지고 있다.

Drawer를 구현할 스크린 상위에 DrawerLayout를 감싸는 것으로 손쉽게 Drawer를 구현할 수 있다.

 

다음은 공식 문서를 참고한 소스코드 예제이다.

  // ~ 생략 ~
  
  const handleDrawerSlide = (status: number) => {
    // outputs a value between 0 and 1
    console.log(status);
  };

  const renderDrawer = () => {
    return (
      <View>
        <Text>I am in the drawer!</Text>
      </View>
    );
  };

  return (
    <SafeAreaView style={{flex: 1}}>
      <DrawerLayout
        drawerWidth={200}
        drawerType="front"
        drawerBackgroundColor="#ddd"
        renderNavigationView={renderDrawer}
        onDrawerSlide={handleDrawerSlide}>
        {children} {/*  하위 컴포넌트들  */}
      </DrawerLayout>
    </SafeAreaView>
  );
  
 // ~ 생략 ~

 

 

 

 

https://docs.swmansion.com/react-native-gesture-handler/docs/api/components/drawer-layout/

 

Drawer Layout | React Native Gesture Handler

This is a cross-platform replacement for React Native's DrawerLayoutAndroid component. It provides a compatible API but allows for the component to be used on both Android and iOS. Please refer to React Native docs for the detailed usage for standard param

docs.swmansion.com

 

 

이외에도 react-native-gesture-handler은 요소를 좌우로 넘겨 이벤트를 발생시키는 Swipeable과 같은 멋진 컴포넌트를 가지는 유용한 라이브러리이다.