From 3e419d671598035b0227d86499cc2d5da3bd71e0 Mon Sep 17 00:00:00 2001 From: Alejandro Gomez Date: Sat, 28 Jan 2023 23:07:37 +0100 Subject: [PATCH] close modal on click outside --- src/Element/LNURLTip.tsx | 2 +- src/Element/Modal.tsx | 22 +++++++++++++++++++--- src/Element/NoteCreator.tsx | 6 ++++-- 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/Element/LNURLTip.tsx b/src/Element/LNURLTip.tsx index 3770e405..b25bf4a5 100644 --- a/src/Element/LNURLTip.tsx +++ b/src/Element/LNURLTip.tsx @@ -225,7 +225,7 @@ export default function LNURLTip(props: LNURLTipProps) { if (!show) return null; return ( - onClose()}> +
e.stopPropagation()}>

{props.title || "⚡️ Send sats"}

{invoiceForm()} diff --git a/src/Element/Modal.tsx b/src/Element/Modal.tsx index 9ae75573..3d56118f 100644 --- a/src/Element/Modal.tsx +++ b/src/Element/Modal.tsx @@ -1,5 +1,5 @@ import "./Modal.css"; -import { useEffect } from "react" +import { useEffect, useRef } from "react" import * as React from "react"; export interface ModalProps { @@ -8,9 +8,25 @@ export interface ModalProps { children: React.ReactNode } +function useOnClickOutside(ref: any, onClickOutside: () => void) { + useEffect(() => { + function handleClickOutside(ev: any) { + if (ref && ref.current && !ref.current.contains(ev.target)) { + onClickOutside() + } + } + document.addEventListener("mousedown", handleClickOutside); + return () => { + document.removeEventListener("mousedown", handleClickOutside); + }; + }, [ref]); +} + export default function Modal(props: ModalProps) { + const ref = useRef(null); const onClose = props.onClose || (() => { }); const className = props.className || '' + useOnClickOutside(ref, onClose) useEffect(() => { document.body.classList.add("scroll-lock"); @@ -18,8 +34,8 @@ export default function Modal(props: ModalProps) { }, []); return ( -
{ e.stopPropagation(); onClose(); }}> -
+
+
{props.children}
diff --git a/src/Element/NoteCreator.tsx b/src/Element/NoteCreator.tsx index 41f51fc3..fb256344 100644 --- a/src/Element/NoteCreator.tsx +++ b/src/Element/NoteCreator.tsx @@ -18,7 +18,6 @@ export interface NoteCreatorProps { setShow: (s: boolean) => void replyTo?: NEvent, onSend?: Function, - onClose?(): void autoFocus: boolean } @@ -90,7 +89,10 @@ export function NoteCreator(props: NoteCreatorProps) { {show && ( - + setShow(false)} + >