import { useRef, useCallback, useState } from "react";
import { ArgsTable, Story, Canvas, Meta } from "@storybook/addon-docs";
import useEventListener from "..";
import "../../__stories__/general-hooks-stories.scss";

<Meta title="Hooks/useEventListener" />

# useEventListener

- [Overview](#overview)
- [Arguments](#arguments)
- [Feedback](#feedback)

## Overview

Attaches a listener to any DOM event on a specific element, firing a provided callback when the event is triggered.

<Canvas>
  <Story name="Overview">
    {() => {
      const ref = useRef(null);
      const [hovered, setHovered] = useState(false);
      const callback = useCallback(
        e => {
          setHovered(true);
        },
        [setHovered]
      );
      useEventListener({ ref, callback, eventName: "mouseenter" });
      return (
        <div ref={ref} className="hooks-reference-element">
          Hover me {hovered ? "Boom!" : undefined}
        </div>
      );
    }}
  </Story>
</Canvas>

## Arguments

<FunctionArguments>
  <FunctionArgument name="options" type="Object">
    <FunctionArgument
      name="ref"
      type="React.MutableRefObject"
      description={
        <>
          A React{" "}
          <a href="https://reactjs.org/docs/hooks-reference.html#useref" target="_blank" rel="noopener noreferrer">
            ref
          </a>{" "}
          object.
        </>
      }
    />
    <FunctionArgument
      name="callback"
      type="(event: Event) => void"
      description="Callback function to execute when the event is fired."
      required
    />
    <FunctionArgument
      name="eventName"
      type="string"
      description={
        <>
          The event to listen to. See{" "}
          <a href="https://developer.mozilla.org/en-US/docs/Web/Events" target="_blank" rel="noopener noreferrer">
            a full list
          </a>{" "}
          for more info.
        </>
      }
      required
    />
    <FunctionArgument
      name="capture"
      type="boolean"
      description="Whether to capture the event before bubbling up or not."
      default="false"
    />
  </FunctionArgument>
</FunctionArguments>
