Search code examples
reactjsradix-ui

button gets fired when react renders it inside a dialog which holds a form with interactive input elements


I am creating a web app with react using shadcn as my ui library. On one page I have a react form and there is one option which is a combobox which when the result you are looking for is not found you can create it yourself, so it displays a button which opens a dialog with the another form which lets you create that element. That button is its on component which can hold another component in to render the desired form like this:

export function CreateButton(props: {
  goToElement: any
  variant?:
    | "default"
    | "destructive"
    | "outline"
    | "secondary"
    | "ghost"
    | "link"
    | null
    | undefined
  title?: string
  description?: string
}) {
  return (
    <>
      <DialogTrigger asChild>
        <Button variant={props.variant}>{props.title}</Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>{props.title}</DialogTitle>
          <DialogDescription>{props.description}</DialogDescription>
        </DialogHeader>
        {props.goToElement}
      </DialogContent>
    </>
  )
}

The initial <Dialog> element is inside the main layout, encasing a react router outlet in which links can render so I do not have to include it on every component.

Now my problem is when the form is just displayed inside of the main app it runs as expected, but when the second form is shown inside the dialog and I try to trigger the rendering of the crate Button inside of the second form it immediately opens the next dialog instead of waiting for the onClick event like when its displayed inside the main app page.

So to describe it in short terms, users writes form => inside the combobox he wants to create the corresponding element before submitting form so when the element is not found so the create element button renders inside the combobox => user clicks on said button and dialog opens with another form. In this case the is also a field with a combobox with the same characteristics as the previous combobox but as soon as the button renders the next dialog with another form instead of letting the user decide.

I tried to capture some basic events like on click or onFocus but cannot seem to find out why this behaviour happens only inside of dialogs, so help would be very wonderful.

I expect the rendering of the button inside of the form which is rendered inside a dialog to not trigger the next dialog.


Solution

  • Alright so I found out what caused the problem.

    In the beginning I said that I encapsulated my react router outlet with the <Dialog> component. this seems to create the problem. I then added the Dialog Component inside the form and it does the job as intended.

    If someone has an answer as to why this behaviour is happening I would be glad to hear from someone more knowledgable.