useModal
🖼 React hook for Modals
Simple, lightweight hook for Modals/Dialogs.
This hook is also isomorphic, meaning it works with SSR (server side rendering).
Features
- SSR (server side rendering) support
- TypeScript support
- 2 dependencies (use-ssr, react-useportal)
- Built in state
Examples
Installation
yarn add use-react-modal or npm i -S use-react-modal
Usage
Basic Usage
import useModal from 'use-react-modal' const App = const isOpen openModal closeModal Modal = return <> <button =>Open Me!</button> isOpen && <Modal> <button =>close</button> Whatever you put here will be centered to the middle of the screen </Modal> </> )
With Provider
import useModal Provider from 'use-react-modal' const MyComponent = const isOpen openModal Modal = return <> <button =>Open Me!</button> isOpen && <Modal> Now whatever you put here will be centered AND have a backdrop with the color specified in the Provider </Modal> </> ) const App = <Provider ='rgba(0, 0, 0, 0.5)'> <MyComponent /> </Portal>
Make sure you are passing the html synthetic event to the openModal
and toggleModal
. i.e. onClick={e => openModal(e)}
ref
Usage with a If for some reason, you don't want to pass around the event
to openModal
or toggleModal
, you can use a ref
like this.
import useModal from 'use-react-modal' const App = const ref openModal closeModal isOpen Modal = return <> /* see below how I don't have to pass the event if I use the ref */ <button = => Open Modal </button> isOpen && <Modal> <p> <button =>Close me!</button> hit ESC or Cool Modal 😜 </p> </Modal> </>
Options
Option | Description |
---|---|
background |
sets the color of the backdrop, if nothing is set, there will be no backdrop |
closeOnOutsideClick |
This will close the modal when not clicking within the modal. Default is true |
closeOnEsc |
This will allow you to hit ESC and it will close the modal. Default is true |
bindTo |
This is the DOM node you want to attach the modal to. By default it attaches to document.body |
isOpen |
This will be the default for the modal being open or closed. Default is false |
onOpen |
This is used to call something when the modal is opened |
onClose |
This is used to call something when the modal is closed |
html event handlers (i.e. onClick ) |
These can be used instead of onOpen . |
Option Usage
const openModal closeModal toggleModal isOpen Modal // if you don't pass an event to openModal, closeModal, or toggleModal, you will need to // put this on the element you want to interact with/click to open the modal targetRef // this allows you to interact directly with the backdrop/overlay backdropRef // this allows you to interact directly with the modal modalRef} =