UNPKG

react-bootstrap-typeahead

Version:
46 lines (45 loc) 1.39 kB
import { useEffect, useState } from 'react'; import { usePopper } from 'react-popper'; const setPopperWidth = { enabled: true, fn: (data) => { data.state.styles.popper.width = `${data.state.rects.reference.width}px`; }, name: 'setPopperWidth', phase: 'write', }; export function getModifiers(props) { const modifiers = [ { enabled: !!props.flip, name: 'flip', }, ]; if (props.align !== 'right' && props.align !== 'left') { modifiers.push(setPopperWidth); } return modifiers; } export function getPlacement(props) { const x = props.align === 'right' ? 'end' : 'start'; const y = props.dropup ? 'top' : 'bottom'; return `${y}-${x}`; } export function useOverlay(referenceElement, options) { const [popperElement, attachRef] = useState(null); const { attributes, styles, forceUpdate } = usePopper(referenceElement, popperElement, { modifiers: getModifiers(options), placement: getPlacement(options), strategy: options.positionFixed ? 'fixed' : 'absolute', }); const refElementHeight = referenceElement?.offsetHeight; useEffect(() => { forceUpdate && forceUpdate(); }, [refElementHeight]); return { ...attributes.popper, innerRef: attachRef, style: styles.popper, }; } export default useOverlay;