React Native의 Modal 컴포넌트는 기존 UI 콘텐츠 위에 별도의 뷰를 띄워 보여주는 기능을 제공합니다. 알림창, 확인 대화상자, 간단한 폼 입력 등 다양한 상황에서 활용할 수 있는 필수 컴포넌트입니다.
Modal 컴포넌트의 기본 구조
Modal의 기본적인 사용 형태는 다음과 같습니다.
<Modal animationType="slide" transparent={true} visible={modalVisible} onRequestClose={() => { Alert.alert("Modal has been closed."); }}> 여기에 콘텐츠 작성</Modal>Modal 컴포넌트를 사용하려면 먼저 react-native에서 임포트해야 합니다.
import { Modal } from "react-native";Modal 창의 주요 Props
Modal 윈도우에서 자주 사용되는 핵심 속성들을 정리하면 다음과 같습니다.
| 번호 | Props 및 설명 |
|---|---|
| 1 | animationType 모달 창이 나타날 때의 애니메이션 효과를 지정합니다. slide(아래에서 위로 슬라이드), fade(서서히 나타남), none(애니메이션 없음) 세 가지 값을 가지는 enum 타입입니다. |
| 2 | onDismiss 모달 창이 닫혔을 때 호출되는 함수를 전달받습니다. |
| 3 | onOrientationChange 모달 창이 표시된 상태에서 기기의 화면 방향(가로/세로)이 변경될 때 호출되는 콜백 함수입니다. |
| 4 | onShow 모달 창이 화면에 나타났을 때 호출되는 함수를 prop 값으로 전달합니다. |
| 5 | presentationStyle 모달 창의 표시 형태를 결정합니다. 사용 가능한 값은 fullScreen, pageSheet, formSheet, overFullScreen 네 가지입니다. |
| 6 | transparent 모달 배경을 투명하게 할지, 아니면 전체 화면을 채울지 결정하는 속성입니다. |
| 7 | visible 모달 창의 표시 여부를 결정합니다. true이면 화면에 나타나고, false이면 숨겨집니다. |
예제 1: 모달 창 띄우기
먼저 Modal 컴포넌트를 임포트합니다.
import { Modal } from "react-native";모달 창을 띄울 때는 원하는 애니메이션 효과를 선택할 수 있습니다. 옵션은 slide, fade, none 세 가지입니다. 아래 예제에서는 텍스트와 버튼이 포함된 간단한 모달 창을 구현해 보겠습니다.
<Modal
animationType="slide"
transparent={true}
visible={isVisible}
>
<View style={styles.centeredView}>
<View style={styles.myModal}>
<Text style={styles.modalText}>Modal Window Testing!</Text>
<Button style={styles.modalButton} title="Close" onPress={() => {setModalVisiblility(false); }}/>
</View>
</View>
</Modal>여기서 isVisible 변수가 visible 속성에 연결됩니다. 기본값은 false이므로, 초기 상태에서는 모달 창이 화면에 나타나지 않습니다. isVisible 변수는 다음과 같이 useState 훅으로 초기화합니다.
const [isVisible, setModalVisiblility] = useState(false);
setModalVisiblility 함수는 isVisible 변수의 값을 true와 false 사이에서 업데이트합니다.
<Modal> 내부에 정의된 Close 버튼은 클릭 시 setModalVisiblility(false)를 호출하여 isVisible을 false로 만들고, 그 결과 모달 창이 사라지게 됩니다.
반대로 모달 창을 띄우려면 <Modal> 외부에 있는 버튼이 setModalVisiblility(true)를 호출하면 됩니다.
<View style={styles.centeredView}>
<Modal
animationType="slide"
transparent={true}
visible={isVisible}
>
<View style={styles.centeredView}>
<View style={styles.myModal}>
<Text style={styles.modalText}>Modal Window Testing!</Text>
<Button style={styles.modalButton} title="Close" onPress={() =>{setModalVisiblility(false); }}/>
</View>
</View>
</Modal>
<Button title="Click Me" onPress={() => {
setModalVisiblility(true);
}}
/>
</View>전체 실행 코드
아래는 모달 창을 열고 닫는 동작이 포함된 완전한 코드입니다.
import React, { useState } from "react";
import { Button, Alert, Modal, StyleSheet, Text, View } from "react-native";
const App = () => {
const [isVisible, setModalVisiblility] = useState(false);
return (
<View style={styles.centeredView}>
<Modal
animationType="slide"
transparent={true}
visible={isVisible}
>
<View style={styles.centeredView}>
<View style={styles.myModal}>
<Text style={styles.modalText}>Modal Window Testing!</Text>
<Button style={styles.modalButton} title="Close" onPress={() =>{setModalVisiblility(false); }}/>
</View>
</View>
</Modal>
<Button title="Click Me" onPress={() => {
setModalVisiblility(true);
}}
/>
</View>
);
};
const styles = StyleSheet.create({
centeredView: {
flex: 1,
justifyContent: "center",
alignItems: "center",
marginTop: 22
},
myModal: {
width:200,
height:200,
margin: 20,
backgroundColor: "white",
borderRadius: 20,
padding: 35,
alignItems: "center",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.30,
shadowRadius: 4,
elevation: 5
},
modalText: {
marginBottom: 20,
textAlign: "center"
},
modalButton: {
marginBottom: 50,
}
});
export default App;실행 결과
위 코드를 실행하면 'Click Me' 버튼을 눌렀을 때 슬라이드 애니메이션과 함께 반투명 배경 위에 흰색 모달 창이 나타나고, Close 버튼을 누르면 모달이 닫히는 것을 확인할 수 있습니다.