ef00732685
- Made the use of `const` and `let` consistent - import required functions and types from 'react' instead of using the `React.` namespace. - Added `Expand` type, which can expand complex types to their "final" result. - Ensured that we use `as const` for DEFAULT_XXX_TAG where we used a string. So that we have the type of `div` instead of `string` for example. - Used `interface` over `type` where possible. I'm personally more of a `type` fan. But the TypeScript recommends `interfaces` where possible because they are faster, yield better error messages and so on.
38 lines
1.0 KiB
TypeScript
38 lines
1.0 KiB
TypeScript
import { RefCallback, useRef, useCallback, useMemo } from 'react'
|
|
import { createPopper, Options } from '@popperjs/core'
|
|
|
|
/**
|
|
* Example implementation to use Popper: https://popper.js.org/
|
|
*/
|
|
export function usePopper(
|
|
options?: Partial<Options>
|
|
): [RefCallback<Element | null>, RefCallback<HTMLElement | null>] {
|
|
let reference = useRef<Element>(null)
|
|
let popper = useRef<HTMLElement>(null)
|
|
|
|
let cleanupCallback = useRef(() => {})
|
|
|
|
let instantiatePopper = useCallback(() => {
|
|
if (!reference.current) return
|
|
if (!popper.current) return
|
|
|
|
if (cleanupCallback.current) cleanupCallback.current()
|
|
|
|
cleanupCallback.current = createPopper(reference.current, popper.current, options).destroy
|
|
}, [reference, popper, cleanupCallback, options])
|
|
|
|
return useMemo(
|
|
() => [
|
|
referenceDomNode => {
|
|
reference.current = referenceDomNode
|
|
instantiatePopper()
|
|
},
|
|
popperDomNode => {
|
|
popper.current = popperDomNode
|
|
instantiatePopper()
|
|
},
|
|
],
|
|
[reference, popper, instantiatePopper]
|
|
)
|
|
}
|