hooks#usePopupClose TypeScript Examples

The following examples show how to use hooks#usePopupClose. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Modal.tsx    From ebs-design with MIT License 5 votes vote down vote up
Modal: React.FC<ModalProps> = ({
  open: isOpen = false,
  mask = true,
  size = 'regular',
  header,
  className,
  title,
  closeOnClickOutside = true,
  children,
  ...props
}) => {
  const [open, setOpen] = React.useState(false);
  const createPortal = usePortal('modal-portal');
  useScrollToggler(open);

  const overlayRef = React.useRef<HTMLDivElement>(null);
  usePopupClose(overlayRef, () => {
    if (closeOnClickOutside) {
      props.onClose?.();
      setOpen(false);
    }
  });

  React.useEffect(() => setOpen(isOpen), [isOpen]);

  React.useEffect(() => {
    const event = ({ key }: KeyboardEvent): void => {
      if (['Escape'].includes(key) && props.onClose !== undefined) {
        props.onClose();
      }
    };

    window.addEventListener('keydown', event);

    return (): void => {
      window.removeEventListener('keydown', event);
    };
  }, []);

  const showHeader = React.useMemo(() => header || title, [header, title]);

  return (
    <>
      {open &&
        createPortal(
          <>
            <Mask />

            <div className={cn(`ebs-modal__wrapper`, className)} ref={overlayRef} {...props}>
              <div className={cn(`ebs-modal`, `ebs-modal__size--${size}`, { 'hide-header': !showHeader })}>
                {showHeader ? (
                  <div className="ebs-modal__header">
                    {title && <h2 className="ebs-modal__title">{title}</h2>}

                    <div className={cn({ 'ebs-modal__header-container': props.onClose })}>{header}</div>
                    {props.onClose && (
                      <Button
                        icon="close"
                        size="small"
                        className="ebs-modal__header--close"
                        type="text"
                        onClick={props.onClose}
                      />
                    )}
                  </div>
                ) : null}

                {children}
              </div>
            </div>
          </>,
        )}
    </>
  );
}