I am conditionally rendering a Modal, with data being rendered into it on the previous click and as soon as the modal is closed, that data is removed from the state. (All the data related to modal is being stored in the parent component).
Now I am using CSSTransition from react-transition-group, to animate the mounting/unmounting of the Modal, code snippet which is calling Modal is like
<CSSTransition
in={modal.status && modal.state === 'MEDIA_INFO_MODAL'}
appear={true}
timeout={200}
nodeRef={modalRef}
classNames="my-node"
unmountOnExit
\>
<Modal ref={modalRef} modalClicker={modalHandler}>{modal.data}</Modal>
</CSSTransition>
And as it can be seen in this codesandbox the Modal component after closing, is still rendered and in my case it is giving error because the modal.data
becomes null
as soon as I hit the close button from the modal, sending null
in the Modal, causing error.
I can't be sure about the rest of your code, but it looks like you have too many things going on. You can see in your sandbox example a clean way to animate a modal in and out.
<CSSTransition
in={modal.status && modal.state === 'MEDIA_INFO_MODAL'}
timeout={200}
classNames="my-node"
unmountOnExit
\>
<Modal modalClicker={modalHandler}>{modal?.data}</Modal>
</CSSTransition>
I do not know of a reason to pass a ref from the transition to the element, so I took it out. This exact method is how I do all my modals with react-transition-group.
Also, when you are accessing properties on an object that changes state to and from null, it is best to use optional chaining when referring to it.
E.g.
modal?.data
It is syntactic sugar for checking if an object exists before accessing its properties
If you absolutely need to keep the component rendered, then you will need to remove unmountOnExit
, but according to your described issue:
modal.data becomes null as soon as I hit the close button
then your issue should be resolved by optional chaining. If you keep the component mounted you will probably need to hide it with css, or make sure there is only null content inside the Modal
component.