Tips for submitting a form remotely using Radix Alert Dialog and the form attribute

Currently, I have integrated a Radix UI's Alert Dialog in my Next.js 13 app to confirm the deletion of a contact from the user's contact list:

Take a look at the Alert Dialog modal here

However, there seems to be an issue with the delete button (the red 'Yes' button) not triggering the onSubmit handler of the form. Upon clicking it, the modal closes without deleting the contact.

The delete button is connected to a remote form through the form attribute:

const DeleteButton = React.forwardRef((props, ref) => {
  return (
    <button ref={ref} type="submit" form="edit-form" {...props}>
      Yes, delete
    </button>
  );
});

This is how the form is structured:


<form id='edit-form' onSubmit={formSubmitHandler}>
 ...form content goes here...
</form>

Below is the structure for the Alert Dialog:


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>
  );
}


I have tried using forwarding refs, forwarding props, and utilizing the asChild prop following the composition section in the documentation but haven't been successful so far.

Unfortunately, the delete button within the Alert Dialog still doesn't trigger the form submission.

If you have any further information or guidance on this matter, please do let me know. Thank you in advance for your assistance.

Answer №1

After reading the explanation provided here, it seems like the recommended approach would be as follows (not tested):

You need to include an onClick event on AlertDialog.Action to prevent the default behavior:

onClick((e) => e.preventDefault()))
.

This should enable your button to successfully submit the form. Additionally, in the onSubmit handler - which I assume is named

formSubmitHandler</code in your case - you would manage the <code>AlertDialog
state by setting the open property to false within your state to programmatically close the dialog.

To implement this, make sure to utilize the open and onOpenChanged props as shown below:

 <AlertDialog.Root open={open} onOpenChange={setOpen}>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to use a media query on a div element to check for the presence of a scroll bar?

A div has been styled with overflow-y: auto, triggering the appearance of a vertical scroll bar when the content exceeds the height of the div. This causes the content to shift horizontally to accommodate the scroll bar, resulting in misalignment with the ...

How to Add Borders to Components in Material UI Using React

Is there a way to add a border only if elevation is 0 in Material-UI within React? The current code snippet applies a border to all cards by default. const customTheme = createTheme({ components: { MuiCard: { styleOverrides: { root: { ...

The x-axis values in Amchart are transitioning rather than shifting

I'm facing an issue with my x-axis values as I'm using real-time amcharts. The x-axis values change every 3 seconds, but instead of smoothly moving, they abruptly change to the next value. I would like it to slide smoothly like this example: htt ...

What is the best way to focus on a specific section of a CSS class name?

Successfully Working Example: HTML: <div class="items"> <div class="item">item 1</div> <div class="prefix-item-suffix">item 2</div> <div class="item">item 3</div> < ...

Dynamic height adjustment for Bootstrap right column

I am struggling to create a layout with a right column using bootstrap. I can't figure out how to achieve the desired arrangement shown in this image. https://i.stack.imgur.com/VaIWD.png I have attempted various methods but the right column does not ...

Is there a way to eliminate the menuArrow from a Select widget in gwt-bootstrap3?

In my current project, using gwt-bootstrap3, I have been attempting to conditionally remove the menu arrow from a Select box. I have experimented with various methods such as: <select:Select ui:field="fieldName" name="fieldName" b:id="fieldName" showM ...

Adaptive text sizing within Microsoft Outlook

I am facing a challenge in making the font size of my email signature responsive. Although VW seems to be the solution, it doesn't seem to work in Outlook. I have attempted using CSS, but it appears that inline CSS might be necessary. However, I am un ...

Next.js production mode prevents CSS from loading properly

Issue Upon building and launching a production build of our application, the CSS fails to load. Inspecting the devtools reveals a multitude of errors and warnings: Possible Causes The problems do not occur when running the app in development mode. Othe ...

Trouble with Styling React-Toastify in TypeScript: struggling to adjust z-index in Toast Container

Currently in the process of developing a React application utilizing TypeScript, I have incorporated the React-Toastify library to handle notifications. However, encountering some challenges with the styling of the ToastContainer component. Specifically, ...

Ways to guide users to specific pages based on their user type

I am in the process of setting up a login system using ReactJS and NodeJS, where users will be redirected based on their usertype. Once I have verified if a user is valid, I need to redirect them according to their usertype. The available usertypes ar ...

Error encountered while trying to import the Turborepo UI package into Next.js: It appears that an appropriate loader may be required

Currently, I am working on a project using next.js 13.1.1 and setting up a monoRepo-based project with turborepo for the first time. My goal is to incorporate: @next/bundle-analyzer @sentry/nextjs @next-pwa When these configurations are not used, everyth ...

Creating a layout with two divs displayed next to each other using CSS

Just when I thought I had it figured out, my two side-by-side divs are not behaving as intended inside the parent div. Why is the orange "Content" div ending up below the navigation bar? Can anyone spot what I did wrong here? Thank you in advance! CSS: ...

Saving items from a FlatList component into AsyncStorage in a React Native application

So, I've got this Flatlist with data loaded from the state. What I'm trying to achieve is that when a user clicks on the heart icon, that particular item gets added to the wishlist using AsyncStorage. I'm kind of stuck on how to implement t ...

Encountering a "Module build failed: Error: ENOENT: no such file or directory" issue when attempting to import Material UI

I recently ran into an issue while developing my Next JS app. Everything was smooth sailing until I added material-ui to the project. After adding material-ui, it started throwing this error repeatedly: ./node_modules/@emotion/styled/dist/styled.browser.es ...

One-of-a-kind Design: Linear Gradient Background Image

Can you help me with Linear Gradient? Is it feasible to incorporate an actual image instead of just displaying a color like #000000 or #ffffff? background-image: -webkit-linear-gradient(30deg, #000000 50%, #ffffff 50%); In the scenario mentioned above ( ...

Distinguishing between a video or image when uploading files in JavaScript

I've been researching whether JavaScript can determine if a file is a video or an image. However, most of the information I found only shows how to accept these types using the input tag. What I really need is for JS to identify the file type and the ...

Developing a secure user authentication process using React.JS and Node.JS

I'm looking to incorporate a login system within the MERN stack that includes three types of logins: 1. Admin login 2. Student Login 3. Faculty Login The admin login will come with default credentials (admin & admin@123), which can be changed if ...

Issue when attempting to animate an SVG point using translateX transformation

I am attempting to create a basic animation using the translate X property on a section of my svg when hovering over the element. Here is the code I have so far: <html> <style> .big-dot:hover { transform: translateX(20px); animat ...

What are the steps to address the Invalid Hook Call issue while working with Material UI?

Having an issue with a MaterialUI Icon in my code as a newcomer to coding. Here is the snippet: import PersonIcon from '@mui/icons-material/Person'; function Header() { return ( <div> <PersonIcon /> <h2>Header file</h2 ...

What is the method for transferring data while redirecting in Express?

Currently in the process of configuring SAML Single Sign On for my React application. The backend utilizes an express / passport setup, while the front end is built with Reactjs. Upon loading the initial Reactjs SPA, it detects that no username is set and ...