Created
December 11, 2018 02:03
-
-
Save pedronauck/9bde16fa78ba945d27f1a66ed2e2f087 to your computer and use it in GitHub Desktop.
usePopper and useHotkeys hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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