Skip to content

Instantly share code, notes, and snippets.

@pedronauck
Created December 11, 2018 02:03
Show Gist options
  • Save pedronauck/9bde16fa78ba945d27f1a66ed2e2f087 to your computer and use it in GitHub Desktop.
Save pedronauck/9bde16fa78ba945d27f1a66ed2e2f087 to your computer and use it in GitHub Desktop.
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