Reputation: 1
I'm using a Radix UI's Alert Dialog to prompt users to confirm that they want to delete a contact from their contact list in my nextjs 13 app:
Screenshot of Alert Dialog modal
However the delete button (red 'Yes, button') is not triggering the onSubmit handler of the form - clicking it just closes the modal without deleting the contact.
The delete button is wired to a form remotely using the form attribute:
const DeleteButton = React.forwardRef((props, ref) => {
return (
<button ref={ref} type="submit" form="edit-form" {...props}>
Yes, delete
</button>
);
});
The form is set up as such:
<form id='edit-form' onSubmit={formSubmitHandler}>
...form contents here...
</form>
The Alert Dialog is as per below:
export default function Modal2({
title,
description,
children,
}) {
return (
<AlertDialog.Root>
<AlertDialog.Trigger asChild>
{children}
</AlertDialog.Trigger>
<AlertDialog.Portal>
<AlertDialog.Overlay className={styles.overlay} />
<AlertDialog.Content className={styles.content}>
<AlertDialog.Title className={styles.title}>
{title}
</AlertDialog.Title>
<AlertDialog.Description className={styles.description}>
{description}
</AlertDialog.Description>
<div className={styles.actions}>
<AlertDialog.Cancel className={`${styles.button} ${styles.cancel}`}>
Cancel
</AlertDialog.Cancel>
<AlertDialog.Action
className={`${styles.button} ${styles.action}`}
asChild
>
<DeleteButton></DeleteButton>
</AlertDialog.Action>
</div>
</AlertDialog.Content>
</AlertDialog.Portal>
</AlertDialog.Root>
);
}
Tried forwarding refs, forwarding props and using the asChild prop as per composition section of docs but to no avail
The delete button in the Alert Dialog still doesn't trigger a form submission.
Please help as have been stuck here for quite sometime. Let me know if any other info required thanks in advance
Upvotes: 0
Views: 1461
Reputation: 1160
If I understand the answer here correctly, you should do the following (haven't tested):
Add an onClick
to AlertDialog.Action
which prevents the default behavior:
onClick((e) => e.preventDefault()))
.
This should allow your button to submit the form, and in the onSubmit
handler which in your case is formSubmitHandler
, you should control the state of the AlertDialog
- you would set open
to false in your state to close the dialog programmatically.
That means you'd also need to start using the open
and onOpenChanged
props like so:
<AlertDialog.Root open={open} onOpenChange={setOpen}>
Upvotes: 1