Skip to content

nathonius/the-captains-hooks

Repository files navigation

The Captain's Hooks

Build Status

A collection of React + TypeScript utility hooks, mostly stolen from the wonderful useHooks.

Hooks

useFocus

Returns a boolean value reflecting the focus state and two methods to apply to the component to be watched.

const ExampleComponent: React.FC = props => {
  const [focused, focusMethods] = useFocus();
  return <input {...focusMethods} value={focused.toString()} readOnly />;
}

Alternatively:

const ExampleComponent: React.FC = props => {
  const [focused, focusMethods] = useFocus();
  return (
    <input
      value={focused.toString()}
      readOnly
      onFocus={focusMethods.onFocus}
      onBlur={focusMethods.onBlur}
    />
  );
}

useHover

Almost identical to useFocus, returns a boolean value reflecting the hover state and two methods to apply to the component to be watched.

const ExampleComponent: React.FC = props => {
  const [hovered, hoverMethods] = useHover();
  return (
    <div {...hoverMethods}>
      {hover.toString()}
    </div>
  );
}

Alternatively:

const ExampleComponent: React.FC = props => {
  const [hovered, hoverMethods] = useHover();
  return (
    <div
      mouseOver={hoverMethods.mouseOver}
      mouseOut={hoverMethods.mouseOut}
    >
      {hover.toString()}
    </div>
  );
}

useOnClickOutside

Calls the given callback only if the click event target is not contained by the given ref's current value.

const ExampleComponent: React.FC = props => {
  const ref = React.useRef<HTMLDivElement>(null);
  const callback = (event: MouseEvent) => alert(`Got event with target ${event.target}`);
  useOnClickOutside(ref, callback);
  return (
    <div>
      <div>
        click me to call callback with event!
      </div>
      <div ref={ref}>
        click me and nothing happens
        <span>click me and nothing still happens!</span>
      </div>
    </div>
  );
}

useScrollTo

Returns a method that scrolls a component with a given ref into view.

const ExampleComponent: React.FC = props => {
  const ref = React.useRef<HTMLDivElement>(null);
  const scrollTo = useScrollTo(ref);

  return (
    <>
      <div id="some-div" ref={ref} />
      <button onClick={scrollTo}>Scroll back to div</button>
    </>
  )
}