Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
usePopper and useHotkeys hooks
import { useEffect } from 'react'
import hotkeys from 'hotkeys-js'
export const useHotkeys = (key: string, cb: () => any, inputs?: any[]) => {
useEffect(() => {
hotkeys(key, cb)
return () => hotkeys.unbind(key)
}, inputs)
}
import { useEffect, useState, useRef } from 'react'
import Popper, { Placement, Data } from 'popper.js'
export interface PopperOpts {
placement?: Placement
offset?: string
flip?: boolean
overflow?: boolean
}
const defaultOpts: PopperOpts = {
placement: 'bottom',
offset: '0, 0',
flip: true,
overflow: true,
}
export const usePopper = (options: PopperOpts) => {
const ref = useRef(null)
const popper = useRef(null)
const [styles, setStyles] = useState({})
const opts = { ...defaultOpts, ...options }
const modifier = (data: Data) => {
setStyles(data.offsets.popper)
return data
}
useEffect(() => {
if (!ref.current || !popper.current) return
const instance = new Popper(ref.current!, popper.current!, {
placement: opts.placement,
removeOnDestroy: true,
modifiers: {
flip: {
enabled: opts.flip,
padding: 16,
},
preventOverflow: {
enabled: opts.overflow,
},
hide: {
enabled: false,
},
applyStyle: {
enabled: false,
},
offset: {
offset: opts.offset,
},
setState: {
order: 900,
enabled: true,
fn: modifier,
},
},
})
return () => instance.destroy()
}, [])
return [ref, popper, styles]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.