Skip to content

chanwoo00106/modal-controller

Repository files navigation

modal-controller

A library that helps with displaying modals in React.
React에서 모달 띄우는 작업을 도와주는 라이브러리입니다.

Installation

# npm
$ npm i modal-controller

# yarn
$ yarn add modal-controller

# pnpm
$ pnpm add modal-controller

How to use

CodeSandbox example code

// main.tsx
import { ModalController, ModalControllerProvider } from 'modal-controller'

const modalController = new ModalController()

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <ModalControllerProvider modalController={modalController}>
      <App />
    </ModalControllerProvider>
  </React.StrictMode>,
)
// Modal.tsx
import { ModalDefaultProps } from 'modal-controller'

interface Props {
  title: string
}

const Modal = ({ resolve, title }: ModalDefaultProps<Props, boolean>) => {
  return (
    <div>
      <h1>{title}</h1>

      <button onClick={() => resolve(false)}>Cancel</button>
      <button onClick={() => resolve(true)}>Ok</button>
    </div>
  )
}

export default Modal
// App.tsx
import { useModalController } from 'modal-controller'
import Modal from './Modal'

function App() {
  const modalController = useModalController()

  const onClick = async () => {
    const result = await modalController.push('Modal', Modal, {
      title: 'wow',
    })

    alert(result)
  }

  return (
    <main>
      <button onClick={onClick}>open modal</button>
    </main>
  )
}

export default App

ModalController Spec

Property Type Description
modalStack Modal[] Returns Modal list
push (key: string, Component: C, props?: P) => Promise Add a Modal
top () => Modal Returns the highest Modal
pop () => void Remove the highest Modal
clear () => void Remove all Modal