react-magma icon indicating copy to clipboard operation
react-magma copied to clipboard

Modal: On Escape doesn't update

Open silvalaura opened this issue 1 year ago • 0 comments

I observed some odd behavior when trying to close the modal by pressing Escape. In the following example, I have the count variable that can be increased in the modal by clicking on the button. When the modal closes via the close icon or click on the background it works as expected and value of the count variable inside the onClose function is updated. But when closing the modal by pressing on Escape value of the count variable is not updating inside onClose and due to the closures count has an old value (that existed when I just opened the modal). I just wondering if there is opened issue for that? Tested it with 4.3.0 version.

https://github.com/cengage/react-magma/assets/91160746/67ab07f2-5397-4f0d-ad9c-c8310fa5660a

import React from "react";
import { Button, Modal, VisuallyHidden } from "react-magma-dom";
export function Example() {
  const [showModal, setShowModal] = React.useState(false);
  const [count, setCount] = React.useState(0);
  const buttonRef = React.useRef();

  console.log("Count: ", count);

  function handleOnClose() {
    console.log("Count on close:", count);
    setShowModal(false);
    buttonRef.current.focus();
  }

  function onClick() {
    setCount((prev) => prev + 1);
  }

  return (
    <>
      <Modal header="Modal Title" onClose={handleOnClose} isOpen={showModal}>
        <Button onClick={onClick}>Add</Button>
      </Modal>
      <Button onClick={() => setShowModal(true)} ref={buttonRef}>
        Show Modal
        <VisuallyHidden>(opens modal dialog)</VisuallyHidden>
      </Button>
    </>
  );
}

I attempted to fix this in branch fix/ModalEscCount. The issue is that this causes onClose to get called twice, so we need a better long term solution.

silvalaura avatar Feb 21 '24 17:02 silvalaura