어쩌다 알게 된 ƪ(•̃͡•̃͡ ƪ

🟦 [React] 모달 창 띄우기 본문

개발/🟦 React

🟦 [React] 모달 창 띄우기

비니_ 2025. 3. 17. 16:55
728x90

처음 만든 모달

 

Modal.jsx

import './Modal.css'

const Modal = ({ isOpen, onClose, title, content, onConfirm, onCancle, width, height }) => {
  if(!isOpen) return null;

  return (
    <div className="modal">
      <div className="modal_inner">
        <div className="modal_content" style={{ width, height }}>
          <div className="modal_header">
            <span className="close" onClick={onClose}>&times;</span>
            <div className="modal_title">{title}</div>
          </div>
          <div className="modal_body">{content}</div>
          <div className="modal_footer">
            {
              onConfirm ?
              <button className='btn btn_style1 modal_confirm neg' onClick={{onCancle}}>취소</button>
              :
              <button className='btn btn_style1 modal_confirm pos' onClick={{onConfirm}}>확인</button>
            }
          </div>
        </div>
      </div>
    </div>
  )
}

export default Modal;

 

App.jsx

import { useState } from 'react'
import Modal from './Modal';

function App() {
  const [isModalOpen, setIsModalOpen] = useState(false);

  const handleOpenModal = () => {
    setIsModalOpen(true);
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
  };

  return (
    <>
      <div>
        <h1>React Modal</h1>
        <button onClick={handleOpenModal}>버튼</button>

        <Modal
          isOpen={isModalOpen}
          onClose={handleCloseModal}
          title="타이틀"
          content={<div className="modal_inquiry_result">등록 완료 되었습니다.</div>}
          onConfirm={handleCloseModal}
          onCancle={handleCloseModal}
          width="400px"
          height="initial"
        />
      </div>
    </>
  )
}

export default App

 

 

하나의 팝업만 뜰 땐 괜찮으나 실제로는 같은 페이지 내에서도 수십개씩 띄워야 하기 때문에

어떻게 코드를 줄일까 생각하고 다시 짠 코드

 

[React] 모달 창 띄우기2_코드 재사용화, 컴포넌트화 시키기

Modal.jsx 👇import './Modal.css'const Modal = ({ isOpen, onClose, title, content, onBtn = [], onCancle, width, height }) => { if(!isOpen) return null; return ( × {title} {content} {onBtn.map((btn, index) => ( {btn.text} )) } )}expor..

dazzle-bini.tistory.com

 

728x90
Comments