How can I close a Reactjs-popup Modal on Submit?

Viewed 1514

i've been creating a form using Reactjs-popup, set as a modal, but I can't seem to find a way to both submit the form AND close the modal. It closes when I click outside the form but it's not very UX... anyone got some tips ? The documentation didn't help much thanks !!

2 Answers

I would make use of the useState hook in React to track if the model is open or closed. You can set the state when you click on your submit button, or when you close the modal by yourself. It should be pretty flexible and should work for your situation.

Quick example to show the idea:

// Create the state hook
const [isOpen, setIsOpen] = useState(false);

// Function to close the modal and submit the form
const handleOnClick = () => {
  setIsOpen(false);
  submitForm();
}


<Modal open={isOpen} />
<Button onClick={handleOnClick} text="Submit button" />

I had the same question, because the modal docs make a child modal element as a function, not a react element.

My typescript was complaining about how "type (close: any)=> Element is not assignable to ReactNode" (eg you can't make the Popup component's child be a function! It has to be a JSX Element!)

I confirmed that using a function as a child is actually intended behavior so I just overrode the typescript errors:

<Popup modal>
(close => ( 
  my ... modal ... that ... uses ... close 
) )  as unknown as ReactNode
</Popup>

and it worked !

So you can use the close function inside your onSubmit function

<Popup modal>
(close => ( 
  <yourModal onSubmit={()=> {oldCode; close() }}></yourModal>
) )  as unknown as ReactNode
</Popup>

Very bad code smell, but if you just need something to work this will do it.

Related