Skip to content

Commit

Permalink
#8 Add hook to detect outside clicks
Browse files Browse the repository at this point in the history
  • Loading branch information
tina-e committed Aug 21, 2022
1 parent 38ea84b commit dfdb192
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
10 changes: 5 additions & 5 deletions src/components/sidebar/Hint.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,12 @@ import {
FloppyDisk,
X,
} from "phosphor-react";
import { useState } from "react";
import { useRef, useState } from "react";
import { Button } from "../Button";
import cx from "classnames";
import { Editor } from "react-draft-wysiwyg";
import { ContentState, convertFromHTML, EditorState } from "draft-js";
import { useOutsideClick } from "../../hooks/use-outside-click";

export interface HintProps {
id: string;
Expand Down Expand Up @@ -45,6 +46,8 @@ export const Hint: React.FC<HintProps> = (hint: HintProps) => {

return EditorState.createWithContent(contentState);
});
const ref = useRef(null);
useOutsideClick(ref, () => setIsMenuOpen(false));

const showReference = (e: React.MouseEvent) => {
//TODO
Expand Down Expand Up @@ -142,10 +145,7 @@ export const Hint: React.FC<HintProps> = (hint: HintProps) => {
</div>
</div>

<div
className="self-end relative"
// onBlur={() => setIsMenuOpen(false)}
>
<div ref={ref} className="self-end relative">
<Button
key="createHint"
bgColor={
Expand Down
25 changes: 25 additions & 0 deletions src/hooks/use-outside-click.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { useEffect } from "react";

export const useOutsideClick = (
ref: React.RefObject<HTMLElement>,
callback: () => void
) => {
useEffect(() => {
const handleClick = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) {
callback();
}
};

document.addEventListener("mousedown", handleClick);
document.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
callback();
}
});

return () => {
document.removeEventListener("mousedown", handleClick);
};
}, [ref, callback]);
};

0 comments on commit dfdb192

Please sign in to comment.