npm.io
0.0.8 • Published 7 years ago

the-captains-hooks

Licence
ISC
Version
0.0.8
Deps
0
Size
18 kB
Vulns
0
Weekly
0

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>
  );
}
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>
    </>
  )
}