Home > Enterprise >  Mui Modal closing on Dispatching action in the Parent Component
Mui Modal closing on Dispatching action in the Parent Component

Time:05-01

I have created a modal component that opens onClick. This component uses a callback from it's parent component that dispatches an action from it's parent component. The modal has a state variable called "open" which is used to decide whether to open the modal or not.

const handleOpen = () => {
props.getDetails(props.dsaId?props.dsaId:props.triggerName)
setOpen(open) 

};

The handleOpen function is called when the button is clicked. As you can see setOpen changes [open] value to true , which in turn should open the Modal.

    props.getDetails(props.dsaId?props.dsaId:props.triggerName)

is used for dispatching an action in the parent component, which in turn will pass the data as props to my child component.

The problem is when i call the callback function from the child component, action dispatched in the parent component causes the parent to rerender , which in turn re-renders the child component setting [open] to false again, which closes the modal.

How do i Keep the modal open , after dispatching the action.

CodePudding user response:

You can move the state of the model up to the parent state. Read[Lifting up the state].

CodePudding user response:

You can keep modal's open state in parent component and pass it in the props to the child component.

const Parent = () => {
    const [childModalOpen, setChildModalOpen] = useState(false);
    return (
        <Child
            modalOpen={childModalOpen}
            onModalChange={(open) => setChildModalOpen(open)}                                                         
            {...otherProps}
         />);
};
const Child = ({ modalOpen, onModalChange }) => {
    const [open, setOpen] = useState(open);

    useEffect(() => {
        setOpen(modalOpen);
    }, [modalOpen]);

    const handleOpen = () => {
        onModalChange(true);
    };
    const handleClose = () => {
        onModalChange(close);
    };

    return (
        <Modal open={} onClose={handleClose}>
            {* children *}
        </Modal>);
};
  • Related