manage modal using global state in react project
Try it out with Storybook
npm i rc-global-modal
- Open and close modal from anywhere in the app(inside
ModalProvider
) - Custom CSS style for modal and overlay
- Ref for modal container and overlay
- Choose animation type and duration for modal
Props | Types | Required | Default | Description |
---|---|---|---|---|
children | React.FC |
✅ | component that will be displayed inside modal | |
id | string | number |
✅ | unique id for modal | |
closeOnOverlayClick | boolean |
❌ | true |
close modal when overlay is clicked |
modalContainerClassName | string |
❌ | class name for modal container | |
overlayClassName | string |
❌ | class name for overlay | |
modalContainerStyle | React.CSSProperties |
❌ | custom style for modal container | |
overlayStyle | React.CSSProperties |
❌ | custom style for overlay | |
closeOnEsc | boolean |
❌ | true |
close modal when esc key is pressed |
modalContainerRef | React.RefObject |
❌ | ref for modal container | |
overlayRef | React.RefObject |
❌ | ref for overlay | |
animationType | 'fade' | 'slideUp' | 'slideDown' | 'slideLeft' | 'slideRight' | 'zoom' |
❌ | fade |
animation type for modal |
animationDuration | number |
❌ | 300 |
animation duration for modal |
- Wrap your app with
ModalProvider
component
import { ModalProvider } from 'rc-global-modal';
function App() {
return (
<ModalProvider>
<Home />
</ModalProvider>
);
}
- Use
Modal
component to display modal(must be insideModalProvider
)
import { Modal } from 'rc-global-modal';
const Home = () => {
return (
<Modal id={1}>
<h1>IdOneModal</h1>
</Modal>
);
};
- Use
openModal
andcloseModal
function to open and close modal(must be insideModalProvider
)
import { Modal, useModal } from 'rc-global-modal';
const Home = () => {
const { openModal, closeModal } = useModal();
return (
<div>
<button onClick={() => openModal(1)}>open Id One modal</button>
<Modal id={1}>
<h1>IdOneModal</h1>
<button onClick={closeModal}>close modal</button>
</Modal>
</div>
);
};
import { Modal, useModal } from 'rc-global-modal';
const Home = () => {
const { openModal, closeModal } = useModal();
return (
<div>
<button onClick={() => openModal(1)}>open Id One modal</button>
<button onClick={() => openModal(2)}>open Id Two modal</button>
<Modal id={1}>
<h1>IdOneModal</h1>
<button onClick={closeModal}>close modal</button>
</Modal>
<Modal id={2}>
<h1>IdTwoModal</h1>
<button onClick={closeModal}>close modal</button>
</Modal>
</div>
);
};
export default Home;
MIT