0.4.0 • Published 3 years ago

use-popper-placement v0.4.0

Weekly downloads
8
License
MIT
Repository
github
Last release
3 years ago

use-popper-placement

A custom React Hook that automagically places your popper (dropdown, tooltip, etc.) inline with your desired trigger (top, bottom, left, or right).

use-popper-placement accepts two refObjects, a trigger and popper, and will automagically align your popper with the trigger. See DEMO for custom tooltip and dropdown examples).

Features

⏳ Saves you time by handling all the annoying positioning logic for you.

⭐️ Flexibility to make your own custom tooltips, dropdowns, etc.

🤔 It's Smart! If the popper will render outside the viewport it will automagically flip the side for you.

Requirement

To use use-popper-placement, you must use react@16.8.0 or greater which includes Hooks.

Installation

$ yarn add use-popper-placement
// or
$ npm i use-popper-placement

Example

NOTE: it's important to set the popper's position to fixed (see DEMO's for custom tooltip and dropdown examples).

import { useRef } from 'react';

const SomeComponent = () => {
  const trigger = useRef(null);
  const popper = useRef(null);
  usePopperPlacement({ trigger, popper });

  return {
    <div ref={trigger}>
      I'm a trigger
      <span ref={popper} style={{ position: 'fixed' }}>
        I'm a popper!
      </span>
    </div>
  };
};

export default SomeComponent;

FULL API

usePopperPlacement({ trigger, popper, direction, margin, resizeOptions }): { placePopper: () => void; }

placePopper: () => void;

  • if for any reason your popper can move around, using the placePopper function (returned from the usePopperPlacement hook) will give you the ability to trigger recomputing it's placement on the fly.
  • use-case: you have an element(s) that has a tooltip inside a container that can scroll, the original dimensions/placement will be incorrect as the user scrolls. In order to account for this you could put a scroll listener on the container and create a debounced placePopper as the callback (don't forget to remove the listener on unmount!).

trigger: RefObject

  • a ref to the trigger element.

popper: RefObject

  • a ref to the popper element.

direction: 'top' | 'topLeft' | 'topRight' | 'bottom' | 'bottomLeft' | 'bottomRight' | 'left' | 'right'

  • defaults to 'top'.

margin: number

  • distance (in px) the popper will appear from the trigger.
  • defaults to 8.

resizeOptions: { handleResize: boolean; debounce: number }

  • if you would like to update the placement on window resize use this option.
  • defaults to { handleResize: false, debounce: 500 }.

License

MIT Licensed

Contributors

This project follows the all-contributors specification. Contributions of any kind welcome!

0.4.1

3 years ago

0.4.0

4 years ago

0.3.0

4 years ago

0.2.4

4 years ago

0.2.3

4 years ago

0.2.2

4 years ago

0.2.1

4 years ago

0.2.0

4 years ago

0.1.0

4 years ago