개발/React Native

[React Native][라이브러리] Modal을 추가하는 아주 쉬운 방법 - react-native-magic-modal

ENFP Jake 2023. 8. 5. 01:10
728x90
반응형

# react-native-magic-modal을 활용한 Modal 구현 방법 소개

- 안녕하세요. Jake입니다. 앱을 개발하는 과정에서 모달은 빼놓을 수 없는. UI 요소 중 하나입니다. RN에서 개발을 좀 해보신 분들이라면, RN에서 모달이 필요하면, react-native의 기본 모달로 직접 구현하거나 react-native-modal 사용하셨을 것입니다. 두가지 모두 많이 사용되는 좋은 Modal이지만, 생각보다 추가 해야 할 코드가 많고, 모달의 Show/Hide 등을 직접 관리 해야 해서 간단한 모달이어도 구현에 손이 많이 갑니다. 본 포스팅에서는 이런 경우에 활용할 수 있는 좋은 대안을 소개하려고 합니다.

 

# Github Page

 

GitHub - GSTJ/react-native-magic-modal: 🦄 A modal library that can be called imperatively from anywhere!

🦄 A modal library that can be called imperatively from anywhere! - GitHub - GSTJ/react-native-magic-modal: 🦄 A modal library that can be called imperatively from anywhere!

github.com

 

 

# 사용방법

- 사용 방법은 간단합니다. 우선 라이브러리를 설치합니다.

yarn add react-native-magic-modal

 

- 그리고 Modal을 관리해 줄 Provider를 상위 컴포넌트에 아래와 같은 형태로 추가합니다.

import { MagicModalPortal } from 'react-native-magic-modal';

export default function App() {
  return (
    <SomeRandomProvider>
      <MagicModalPortal />  // <-- On the top of the app component hierarchy
      <Router /> // Your app router or something could follow below
    </SomeRandomProvider>
  );
}

 

- 그리고 나서는 모달에 쓰일 컴포넌트는 자유롭게 만들어 주시면 됩니다. 가령 컨펌을 위한 모달을 아래와 같이 구현했다면, 해당 모달을 보여주기 원하는 이벤트에서 magicModal.show()를 호출하면 끝입니다. 그리고 모달을 숨겨야 하는 이벤트에서 magicModal.hide() 호출 해주시면 됩니다. 앞에서 추가한 Provider보다 하위 컴포넌트에서는 자유롭게 호출이 가능하며, 연속으로 호출 할 수도 있습니다. 또한 비동기로 처리할 수 있다는 것도 장점 중 하나입니다.

import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { MagicModalPortal, magicModal } from 'react-native-magic-modal';

const ConfirmationModal = () => (
  <View>
    <TouchableOpacity onPress={() => magicModal.hide({ success: true })}>
      <Text>Click here to confirm</Text>
    </TouchableOpacity>
  </View>
);

const handleConfirmationFlow = async () => {
  const result = await magicModal.show(ConfirmationModal);
};

export const MainScreen = () => {
  return (
    <View>
      <TouchableOpacity onPress={handleConfirmationFlow}>
        <Text>Start the modal flow!</Text>
      </TouchableOpacity>
    </View>
  );
};

 

# 마치며

- 직접 React Native로 개발한 제 뽀모캣(뽀모도로 타이머 앱)에서도 모든 모달을 이 라이브러리로 구현하였으며, 많은 시간을 절약할 수 있었습니다. 아마 앞으로도 아주 디테일한 부분까지 모달을 컨트롤 해야 하는 경우가 아니라면, 거의 이 라이브러리를 계속 활용하게 될 것 같습니다. 그정도로 만족도가 높았기에 꼭 한 번 사용해 보시길 추천드립니다


728x90
반응형