// store the modal component in a context
const ModalContext = React.createContext(null)
/**
* Simplify the access to the ModalContext by creating a custom hook
*/
const useSetModal = () => {
const handleSetComponent = React.useContext(ModalContext)
return handleSetComponent
}
/**
* App is responsible for storing the component we're displaying in a Modal window
* It then passes the setter function into the ModalContext
* We consume the setter function in the useSetModal() hook
*/
function App () {
const [modalComponent, setModalComponent] = React.useState(null)
return (
<ModalContext.Provider value={setModalComponent}>
<CustomButton />
{modalComponent && (
<Modal component={modalComponent} />
)}
</ModalContext.Provider>
)
}
function CustomButton () {
// With a custom hook, you can access the modal setting function from anywhere
const handleSetModal = useSetModal()
const handleOpenForm = () => {
// pass the component you wish to render to the setter function
handleSetModal(<CustomForm userId="123" />)