React hook for showing modal windows
npm install react-modal-hook



> Syntactic sugar for handling modal windows using React Hooks.
This library does not provide any UI, but instead offers a convenient way to render modal components defined elsewhere.
For a simple modal component check out react-modal, which works well with this library.
- Install
- Usage
- Updating Modals
- Animated Modals
- License
``bash`
npm install --save react-modal-hook
Use ModalProvider to provide modal context for your application:
`jsx
import React from "react";
import ReactDOM from "react-dom";
import { ModalProvider } from "react-modal-hook";
import App from "./App";
ReactDOM.render(
document.getElementById("root")
);
`
Call useModal with the dialog component of your choice. Example using react-modal:
`jsx
import React from "react";
import ReactModal from "react-modal";
import { useModal } from "react-modal-hook";
const App = () => { Modal content
const [showModal, hideModal] = useModal(() => (
));
return ;
};
`
Second argument to useModals should contain an array of values referenced inside the modal:
`jsx
const App = () => {
const [count, setCount] = useState(0);
const [showModal] = useModal(
() => (
The count is {count}
),
[count]
);
return ;
};
`
Modals are also functional components and can use react hooks themselves:
`jsx
const App = () => {
const [showModal] = useModal(() => {
const [count, setCount] = useState(0);
return (
The count is {count}
);
});
return ;
};
`
Use TransitionGroup as the container for the modals:
`jsx
import React from "react";
import ReactDOM from "react-dom";
import { ModalProvider } from "react-modal-hook";
import { TransitionGroup } from "react-transition-group";
import App from "./App";
ReactDOM.render(
document.getElementById("root")
);
`
When TransitionGroup detects of one of its children removed, it will set its in prop to false and wait for onExited callback to be called before removing it from the DOM.
Those props are automatically added to all components passed to useModal. You can can pass them down to CSSTransition or modal component with transition support.
Here's an example using Material-UI's Dialog:
`jsx
import React from "react";
import { useModal } from "react-modal-hook";
import { Button, Dialog, DialogActions, DialogTitle } from "@material-ui/core";
const App = () => {
const [showModal, hideModal] = useModal(({ in: open, onExited }) => (
));
return ;
};
``
MIT © mpontus