|
1 | | -import { useState, useEffect, useRef } from "react"; |
2 | 1 | import { TriangleDownIcon } from "@radix-ui/react-icons"; |
3 | 2 | import BookmarksPopover from "./BookmarksPopover"; |
| 3 | +import { useRef, useState } from "react"; |
4 | 4 | import { useOnClickOutside } from "../lib/hooks"; |
5 | 5 |
|
6 | | -export default function Bookmarks() { |
7 | | - // also called local state |
| 6 | +export default function BookmarksButton() { |
8 | 7 | const [isOpen, setIsOpen] = useState(false); |
9 | 8 | const buttonRef = useRef<HTMLButtonElement>(null); |
10 | 9 | const popoverRef = useRef<HTMLDivElement>(null); |
11 | | - |
12 | | - // hooks for common use cases are available (show google results) |
13 | | - |
14 | | - // detect click outside of the bookmarks list with own solution, without ref |
15 | | - // useEffect(() => { |
16 | | - // function handleClick(event: MouseEvent) { |
17 | | - // const target = event.target as HTMLElement; |
18 | | - // if ( |
19 | | - // !target.closest(".bookmarks-popover") && |
20 | | - // !target.closest(".bookmarks-btn") |
21 | | - // ) { |
22 | | - // setIsOpen(false); |
23 | | - // } |
24 | | - // } |
25 | | - |
26 | | - // document.addEventListener("click", handleClick); |
27 | | - |
28 | | - // return () => document.removeEventListener("click", handleClick); |
29 | | - // }, []); |
30 | | - |
31 | | - // detect click outside of the bookmarks list with own solution, with ref |
32 | | - // useEffect(() => { |
33 | | - // function handleClick(event: MouseEvent) { |
34 | | - // const target = event.target as HTMLElement; |
35 | | - // if ( |
36 | | - // // use ref to check if the click is inside the popover |
37 | | - // !popoverRef.current?.contains(target) && |
38 | | - // // use ref to check if the click is inside the button |
39 | | - // !buttonRef.current?.contains(target) |
40 | | - // ) { |
41 | | - // setIsOpen(false); |
42 | | - // } |
43 | | - // } |
44 | | - |
45 | | - // document.addEventListener("click", handleClick); |
46 | | - |
47 | | - // return () => document.removeEventListener("click", handleClick); |
48 | | - // }, []); |
49 | | - |
50 | | - // use hook |
51 | 10 | useOnClickOutside([buttonRef, popoverRef], () => setIsOpen(false)); |
52 | 11 |
|
53 | 12 | return ( |
54 | 13 | <section> |
55 | 14 | <button |
56 | 15 | ref={buttonRef} |
57 | | - onClick={() => setIsOpen(!isOpen)} |
| 16 | + onClick={() => setIsOpen((prev) => !prev)} |
58 | 17 | className="bookmarks-btn" |
59 | 18 | > |
60 | 19 | Bookmarks <TriangleDownIcon /> |
|
0 commit comments