In case your modal open/close/update logic sucks - grab & use this modal manager context.
import * as React from 'react'
export const ModalManagerContext = React.createContext({
handleOpenModal: () => {},
handleCloseModal: () => {},
handleChangeModalData: () => {},
handleUpdateModalData: () => {},
isOpen: false,
modalData: {}
})
const ModalManagerContextProvider = ({ children }) => {
const [modalState, handleChangeState] = React.useState({
isOpen: false,
data: {}
})
const handleOpenModal = (data = {}) => {
handleChangeState(prevState => ({
isOpen: true,
data: {
...prevState.data,
...data
}
}))
}
const handleCloseModal = () => {
handleChangeState({ isOpen: false, data: {} })
}
const handleChangeModalData = (data = {}) => {
handleChangeState(prevState => ({ ...prevState, data }))
}
const handleUpdateModalData = (data = {}) => {
handleChangeState(prevState => ({ ...prevState, data: { ...prevState.data, ...data } }))
}
return (
<ModalManagerContext.Provider
value={{
handleOpenModal,
handleCloseModal,
handleChangeModalData,
handleUpdateModalData,
isOpen: modalState.isOpen,
modalData: modalState.data
}}
>
{children}
</ModalManagerContext.Provider>
)
}
export default ModalManagerContextProvider
Check this 🍬 as well: React click outside hook.
More tips and best practices on my twitter.
Feedback is appreciated. Cheers!
Top comments (0)