ShadCn Dialog - running code onClose

Hey, wondering if anyone can help me to understand how this might work - I've got a dialog that contains a form. I've got a close dialog button in the dialog that runs some code, however if the user closes the dialog by clicking outside it, the code isn't run. How might I configure the dialog to run this code when the form is closed by clicking outside?
Solution:
Dialog – Radix Primitives
A window overlaid on either the primary window or another dialog window, rendering the content underneath inert.
Jump to solution
11 Replies
hyhy
hyhy12mo ago
Dialog and start of form
No description
dan
dan12mo ago
the <Dialog> component has a prop called onOpenChange (check its props i can’t remember the exact name). but you can use that as the callback for when it gets opened/closed
Solution
dan
dan12mo ago
Dialog – Radix Primitives
A window overlaid on either the primary window or another dialog window, rendering the content underneath inert.
hyhy
hyhy12mo ago
amazing, thanks so much will give it a test tomorrow and mark as complete This is almost working for me, but I'm running into an issue where submitting the form closes it and I can't differentiate between whether the form has been submitted or has been closed without submitting Is there a pattern to distinguish between the two?
hyhy
hyhy12mo ago
I've got my submit button in a dialog close
No description
hyhy
hyhy12mo ago
and then the dialog itself
No description
hyhy
hyhy12mo ago
I was hoping I might be able to check the mutation state in the onClose function but I think this is happening first
Lopen
Lopen12mo ago
Add open props to your dialog Then manually control your state
hyhy
hyhy12mo ago
this is working better, but i'm running into some weird rendering stuff with the form, it looks like it's being opened twice?
No description
No description
No description
dan
dan12mo ago
yea if you're controlling the open prop manually then you'll have to handle clicking off the dialog (if you want that functionality) or leave it. if you control open prop, onOpenChange still gets called. Best thing to do if you control open is to remove the onOpenChange and have the cloes button / save close the model (by setting the state of open)
hyhy
hyhy12mo ago
Looks good, I think the rendering issue is down to some funky useState stuff so will have a play with that not sure why but this issue from yesterday seems to be gone? idk
Want results from more Discord servers?
Add your server