react-modal-helper
v2.0.0-beta.1
Published
A utility to make the use of modals painless
Downloads
17
Readme
react-modal-helper
An utility to make the use of modals painless
Install
npm install --save react-modal-helper
Usage
Create the helper
import React, {Component} from 'react'; import {createModalAdapter} from 'react-modal-helper'; import Modal from 'react-modal'; //<-- using react-modal here but you could use any modal component of your choice // create an adapter to render any modal implementation of your choice export const ModalAdapter = createModalAdapter(({isOpen, children}) => ( <Modal isOpen={isOpen} ariaHideApp={false}> {children} </Modal> ));
use the
useModal
hook call theopen()
with any component to render it as modal. Render the ModalRenderer component to allow it to be displayedimport React, {Component} from 'react'; import {useModal} from 'react-modal-helper'; const App = () => { const {ModalRenderer, open} = useModal(ModalAdapter); const onClick = () => { open(<AnyComponent />); }; return ( <> <ModalRenderer /> </> ); };
Closing the modal. Get access to the modal context using
useModalContext
hookimport {useModalContext} from 'react-modal-helper' const MyComponent = ()=>{ const {close} = useModalContext(); ... // call the close close(); ... return <div>My component</div> }
Alternatively, the
open()
function fromuseModal()
returns the modalHandleconst {close} = open(<MyComponent />);
Modifying close behaviour. E.g. asking user to confirm before close
import {useModalContext} from 'react-modal-helper' import {useCallback} from 'react'; const MyComponent = ()=>{ const onBeforeClose = useCallback((event, forceClose)=>{ event.preventDefault(); if(confirm("Are you sure?")){ forceClose(); } }); const {close} = useModalContext({onBeforeClose}); const onClick = ()=>{ close(); } return <div>My component <button onClick={onClick}>Close!</button></div> }
License
MIT © crownie