Function useEvent

  • Provides a wrapper around the EventListener API. Use the return value to define the event target.

    Type Parameters

    • T extends EventTarget

      The type of the event target.

    Parameters

    Returns Dispatch<SetStateAction<null | T>>

    SetStateAction - A function which is used to assign the event target for convenience. The returned value can be used like a ref when the target is an HTMLElement. If the target is the window or document, you can use it like a regular useState setter.

    const DemoUseEvent = () => {
    const clickTarget = useEvent<HTMLDivElement>("click", (e) => {
    const t = (e.target as HTMLDivElement);
    t.style.backgroundColor = t.style.backgroundColor === "red" ? "green" : "red";
    });

    const windowTarget = useEvent("scroll", _ => console.log("scroll"));
    useEffect(() => windowTarget(document), [windowTarget]);

    return (
    <div
    ref={clickTarget}
    style={{ height: "150vh" }}
    >
    Click me :)
    </div>
    );
    };