KassyLog

자주 사용하는 react-native 태그 알아보기 -Modal 본문

react-native

자주 사용하는 react-native 태그 알아보기 -Modal

Kassy_kim 2023. 1. 3. 17:21

리액트에서는 모달을 만들기위해서 따로 컴포넌트를 만들거나 css의 (나름) 공수를 들였어야 했는데 리액트네이티브에서는 자체적으로 제공하는 모달이 있어서 아주 편리하게 모달을 만들 수 있다.

 

개인적으로 react-native를 활용하면서 가장 편하다고 생각하는 부분이다.

 

 

Modal · React Native

The Modal component is a basic way to present content above an enclosing view.

reactnative.dev

import React, { useState } from "react";
import { Alert, Modal, StyleSheet, Text, Pressable, View } from "react-native";

const App = () => {
  const [modalVisible, setModalVisible] = useState(false);
  return (
    <View style={styles.centeredView}>
      <Modal
        animationType="slide"
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => {
          Alert.alert("Modal has been closed.");
          setModalVisible(!modalVisible);
        }}
      >
        <View style={styles.centeredView}>
          <View style={styles.modalView}>
            <Text style={styles.modalText}>Hello World!</Text>
            <Pressable
              style={[styles.button, styles.buttonClose]}
              onPress={() => setModalVisible(!modalVisible)}
            >
              <Text style={styles.textStyle}>Hide Modal</Text>
            </Pressable>
          </View>
        </View>
      </Modal>
      <Pressable
        style={[styles.button, styles.buttonOpen]}
        onPress={() => setModalVisible(true)}
      >
        <Text style={styles.textStyle}>Show Modal</Text>
      </Pressable>
    </View>
  );
};

const styles = StyleSheet.create({
  centeredView: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 22
  },
  modalView: {
    margin: 20,
    backgroundColor: "white",
    borderRadius: 20,
    padding: 35,
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5
  },
  button: {
    borderRadius: 20,
    padding: 10,
    elevation: 2
  },
  buttonOpen: {
    backgroundColor: "#F194FF",
  },
  buttonClose: {
    backgroundColor: "#2196F3",
  },
  textStyle: {
    color: "white",
    fontWeight: "bold",
    textAlign: "center"
  },
  modalText: {
    marginBottom: 15,
    textAlign: "center"
  }
});

export default App;

위 코드의 예시를 살펴보면

centeredView는 모달의 뒷배경이 되는 가장 상위 컴포넌트이며

그 아래의 Modal 태그를 활용하여 위 그림과 같은 모달 모양을 만들 수 있다.

 

애니메이션 타입은 slide, fade, none 총 3가지로 구성되어있다.