[react-native] 공통 모달 만들기 & 컴포넌트 props로 넘겨주기

swanious·2021년 4월 27일
1

react-native: 0.64.0

재사용을 위해 컴포넌트 자체를 props로 넘겨주는 공통 모달을 만들었다.
공통적으로 사용할 수 있도록 /src/components/common 폴더에 ModalComponent.js 파일 생성

공통 modal 컴포넌트

const ModalComponent = ({
  showModal,
  setShowModal,
  children, // 컴포넌트를 자식으로 넘겨받는다.
}) => {
  return (
    <>
      {showModal ? (
        <View style={styles.centeredView}>
          <Modal
            animationType="fade"
            transparent={true}
            visible={showModal}
            onRequestClose={() => {
              setShowModal(!showModal);
            }}>
            <View style={styles.centeredView}>
              <View style={styles.modalView}>{children}</View>
            </View>
          </Modal>
        </View>
      ) : null}
    </>
  );
};

모달은 props로 3개의 객체를 받는다.

  1. showModal(boolean)
  2. setShowModal(Function)
  3. children(Component)

각각 모달의 상태, 상태를 변경할 함수, 컴포넌트(children)
상위 컴포넌트에서 상태가 true가 되면 모달이 동작하고, 자식으로 받은 컴포넌트를 모달에 띄운다.

에러

이전 react 프로젝트에서는 children={<AnotherComp />} 형식으로 컴포넌트를 바로 넘겼는데, react-native에서는 다음과 같은 오류가 발생했다.

Do not pass children as props. Instead, nest children between the opening and closing tags.

props로 children을 보내지 말고, 대신에 <공통모달><AnotherComp /></공통모달> 형식으로 사용하세요 ! 라는 의미.

아래와 같이 코드를 고친 후 테스트를 해보니 정상동작했다.


function MYComp() {
	// 모달의 상태
	const [showModal, setShowModal] = useState(false);
	const openModal = () => {
	  setShowModal((prev) => !prev);
	};
	
	// 1. 클릭하면,
	<Button onPress={openModal}>
	  <Text>모달 열기</Text>
	</Button>
	
	...
	// 2. 모달에 데이터를 넘겨준다.
	<ModalComponent showModal={showModal} setShowModal={setShowModal}>
	  <넘겨줄 컴포넌트 />
	</ModalComponent>
	...
}

결과

공통모달 컴포넌트에서 콘솔을 찍어보면 아래처럼 컴포넌트가 잘 온다.

profile
TIL 기록을 위한 블로그

0개의 댓글