Showing and hiding a modal window in Grafana 7

Hi guys,

is there any documentation of how to use the Modal React Component in Grafana 7.x.?

I am developing a panel plugin and I managed to show a modal (to display a dialogue) in the plugin but I am not sure how to add a button and a corresponding callback, e.g. to close the modal. Maybe it is my lack of React knowledge, but I don’t get if I need to use the Modal component directly or maybe the ModalsProvider class which provides showModal / hideModal functions?

How my code looks like:

import { Modal, Button } from '@grafana/ui';

export const MyPanel: React.FC<Props> = ({ options, data, width, height }) => {

  return (
    <Modal title="My Message" isOpen={true}>
      {modalBody}
      <Button variant="primary" onClick={onModalClose}>
        Close
      </Button>
    </Modal>
  )
};

How would you implement onModalClose?
Do I have to take a different approach to display and interact with a modal window?

Any help appreciated.

Best, Tobias

Hi,

The documentation for the Modal, along with other grafana-ui components, is available in our storybook: https://developers.grafana.com/ui/latest/index.html?path=/docs/overlays-modal--basic.

We do not have a modal provider, so you’ll need to manage the open/close state manually, for example by using useState hook from React:

export const MyPanel: React.FC<Props> = ({ options, data, width, height }) => {
  const [modalIsOpen, setModalIsOpen] = useState(false);

  const onModalClose = () => {
    setModalIsOpen(false);
  };

  return (
    <div>
      <Button onClick={() => setModalIsOpen(true)}>Open modal</Button>
      <Modal title="My Message" isOpen={modalIsOpen}>
        {modalBody}
        <Button variant="primary" onClick={onModalClose}>
          Close
        </Button>
      </Modal>
    </div>
  );
};
1 Like

Great, thanks. The React hook was exactly what I was missing. It can also been used in the onDismiss callback to close the modal.

<Modal title="My Message" isOpen={modalIsOpen} onDismiss={onModalClose}>
  ...
</Modal>