Search code examples
reactjsdialogmodal-dialogconfirm

React JS, calling function and closing a dialog on click


I am totally new to React. I had to edit someone's code to add new fuctionality.

On click of link, Code shows a confirmation dialog using modal. When user clicks Yes it should clear text in an area(by calling a function) and then close the dialog, when clicking on cancel dialog should simply close.

I modified the code so that, the cancel button is working fine. But when I am clicking on yes, It is calling the function and clearing the text but not closing the dialog. My code below.

    function ConfirmModal({resetNewQuery, visible, onClose }) {
    
 
  return (
    <>
      <Modal
        width={500}
        title="Confirmation"
        visible={visible}
        onClose={onClose}
      >
        <div><b>Are you sure you want to clear query? All the contents will be deleted!</b></div>
        <div/>
        <div/>
      <Button size="btnsm" variant="primary" onClick={()=>resetNewQuery(),{onClose}}>Yes</Button>
        <Button size="btnsm" variant="primary" onClick={onClose}>Cancel</Button>
      </Modal>
    </>
  );
}

Code for the modal

    function Modal({ title, visible, onClose, width, children }) {
  if (visible) {
    return (
      <Dialog
        aria-label={title}
        onDismiss={onClose}
        className={styles.Dialog}
        style={{
          width,
        }}
      >
        <div className={styles.titleWrapper}>
          <span>{title}</span>
          {onClose && (
        
            <div class="iconwrapper" onClick={onClose}>
              <CloseIcon />
            </div>
          )}
        </div>
        <div className={styles.dialogBody}>{children}</div>
      </Dialog>
    );
  }
  return null;
}

How can achieve to clear the query and close the dialog on clicking yes.


Solution

  • hi there @Sudiv the problem is here

    <Button size="btnsm" variant="primary" onClick={()=>resetNewQuery(),{onClose}}>Yes</Button>
    

    when you pass a callback to onClick you need to open curly braces if you want to call multiple functions

    onClick={() => {
     resetQuery();
     onClose();
    }}
    

    or you could have a handler on your component something like

    onClick={() => onClickHanlder()}
    
    onClickHandler = () => {
     resetQuery();
     onClose();
    }