[React] React Modal

seungyeon·2021년 4월 2일
16

React

목록 보기
1/2

react-modal

Accessible modal dialog component for React.JS

React에서는 모달창을 쉽게 구현할 수 있도록 Modal 객체를 제공하는 react-modal 라이브러리를 지원하고 있다. 모달은 자주 사용하게 될 아이인 만큼 이번 기회에 리액트에서 모달을 구현하는 쉽고 간편한 방법을 정리해보겠다.

설치하기

리액트 앱 폴더에서 터미널창에 아래 명령어 중 하나를 입력해 react-modal을 설치해주자.

$ npm install react-modal
$ yarn add react-modal

기본 사용법

기본적인 Modal 사용법을 알아보자.

파일 상단에서 react-modal로부터 Modal 객체를 import해주자.

// App.js
import Modal from 'react-modal';

isOpen={boolean}

isOpenModal 객체에 필수로 있어야 하는 속성으로, 모달이 표시되어야하는지 여부를 나타낸다.

//...

function App() {
  return (
    <Modal isOpen={true}>
      This is Modal content
    </Modal>
  )
}

Modal 태그의 isOpen 속성값(boolean)에 따라 모달창이 표시될 지 여부를 컨트롤 할 수 있다. isOpen 값을 false로 바꾸면 모달창이 표시되지 않는다.

state로 Modal 컨트롤하기

우리가 익숙한 모달창은 주로 버튼 클릭 이벤트로 등장한다. useState를 사용해 모달의 isOpen 속성값을 상태로 관리해주면 이벤트에 콜백함수로 상태변경함수를 줘서 모달을 컨트롤 할 수 있다.

import React, { useState } from 'react';
import Modal from 'react-modal';

function App() {
  const [modalIsOpen, setModalIsOpen] = useState(false);
  return (
    <>
      <button onClick={()=> setModalIsOpen(true)}>Modal Open</button>
      <Modal isOpen={true}>
        This is Modal content
        <button onClick={()=> setModalIsOpen(false)}>Modal Open</button>
      </Modal>
    </>
  )
}  

onRequestClose={callback}

오버레이 부분을 클릭하거나 또는 Esc 키를 누를 시 모달 창이 닫히게 하려면 onRequestClose 속성값으로 isOpen 속성값을 false로 바꿔주는 콜백함수를 주면 된다.

// ...생략
<Modal isOpen={modalIsOpen} onRequestClose={() => setModalIsOpen(false)}>
//... 생략

shouldCloseOnOverlayClick={boolean}

오버레이 클릭은 막고 Esc 키만으로 모달창을 닫고 싶다면,
shouldCloseOnOverlayClick 속성값을 false로 주면 된다.

Modal.setAppElement(element)

여기까지 하면 Console에 다음과 같은 에러가 발생한다.

모달이 열렸을 때 화면을 바라보고 있는 사용자가 모달창이 아닌 다른 컴포넌트의 content를 바라보지 않도록 하기 위해 숨겨줄 엘리먼트를 정의해주는 것이다.

예시에서는 모달이 열렸을 때 #root 엘리먼트를 숨겨주어야 하기 때문에 App.js에 아래의 코드를 적어주면 된다.

// index.js
const rootElement = document.getElementById("root");
ReactDOM.render(
  <StrictMode>
    <App />
  </StrictMode>,
  rootElement
);

// App.js
Modal.setAppElement('#root')

Modal의 스타일을 정의해주는 방법은 3가지가 있다.
1. Inline Styles
2. Classes
3. Transitions

이번에는 Inline Styles를 사용하는 방법을 정리해보자.

Inline Styles

Modal에 style 속성에 contentoverlay 키를 이용해 모달의 content와 overlay 영역을 각각 스타일링 할 수 있다. style 속성을 통해 정의한 값은 모달의 스타일 기본값과 병합된다.

기본 스타일은 Modal.defaultStyles 객체에 정의되어 있으며 그 값은 아래와 같다.

<Modal
  ...
  style={{
    overlay: {
      position: 'fixed',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      backgroundColor: 'rgba(255, 255, 255, 0.75)'
    },
    content: {
      position: 'absolute',
      top: '40px',
      left: '40px',
      right: '40px',
      bottom: '40px',
      border: '1px solid #ccc',
      background: '#fff',
      overflow: 'auto',
      WebkitOverflowScrolling: 'touch',
      borderRadius: '4px',
      outline: 'none',
      padding: '20px'
    }
  }}
  ...
>

overlaycontent에 대한 CSS 클래스를 지정하면 해당 구성 요소의 기본 스타일이 비활성화된다.

더 자세한 내용은 react-modal Styles 공식문서에서 확인할 수 있다.


Reference

1개의 댓글

comment-user-thumbnail
2022년 11월 9일

A reactive model and process are fit for the individuals. Things of the https://academadvisor.com/best-essay-writing-services in the shadows. The pattern is held for the cited material. Joy is ensured for the ornament for the ital. path for the things.

답글 달기