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).
⏳ 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.
To use use-popper-placement, you must use [email protected] or greater which includes Hooks.
$ yarn add use-popper-placement
// or
$ npm i use-popper-placementNOTE: 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;usePopperPlacement({ trigger, popper, direction, margin, resizeOptions }): { placePopper: () => void; }
- if for any reason your popper can move around, using the placePopperfunction (returned from theusePopperPlacementhook) 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 scrolllistener on the container and create a debouncedplacePopperas the callback (don't forget to remove the listener on unmount!).
- a ref to the trigger element.
- a ref to the popper element.
direction: 'top' | 'topLeft' | 'topRight' | 'bottom' | 'bottomLeft' | 'bottomRight' | 'left' | 'right'
- defaults to 'top'.
- distance (in px) the popper will appear from the trigger.
- defaults to 8.
- if you would like to update the placement on window resize use this option.
- defaults to { handleResize: false, debounce: 500 }.
MIT Licensed
This project follows the all-contributors specification. Contributions of any kind welcome!