An utility to make the use of modals painless
npm install --save react-modal-helper
-
Create the helper
import React, {Component} from 'react'; import {createModalHelper} from 'react-modal-helper'; import Modal from 'react-modal'; //<-- using react-modal here but you could use any modal component of your choice // create the helper and export it. it will be used later export const modal = createModalHelper(({isOpen, children}) => ( <Modal isOpen={isOpen} ariaHideApp={false}> {children} </Modal> ));
-
Wrap your app with ModalProvider
import React, {Component} from 'react'; import {ModalProvider} from 'react-modal-helper'; // create the helper <ModalProvider> <App /> </ModalProvider>;
-
use the modal helper you created in step 1
// it takes the component you want to render as first argument and its props as second arg modal(MyComponent, {someProp: 'some prop value'});
-
Closing the modal. Get access to the modal context using useModalHandle hook
import {useModalHandle} from 'react-modal-helper' const MyComponent = ()=>{ const {close} = useModalHandle(); ... // call the close close(); ... return <div>My component</div> }
Alternatively, the
modal()
helper function returns the modalHandleconst {close} = modal(MyComponent, {someProp: 'some prop value'});
MIT © crownie