Skip to content

Instantly share code, notes, and snippets.

@reyronald
Last active August 3, 2020 15:40
Show Gist options
  • Save reyronald/7616a3fa6a63b75a5e1e6abe8d8bb053 to your computer and use it in GitHub Desktop.
Save reyronald/7616a3fa6a63b75a5e1e6abe8d8bb053 to your computer and use it in GitHub Desktop.
import React from 'react'
import { Overlay, Popover } from 'react-bootstrap'
function useTooltip() {
const mountNodeRef = React.useRef<HTMLDivElement>()
React.useEffect(() => {
const mountNode = document.createElement('div')
mountNodeRef.current = mountNode
return () => {
if (document.body.contains(mountNode)) {
document.body.removeChild(mountNode)
}
}
}, [])
const openPopover = (component: React.SFCElement<any>) => {
if (!mountNodeRef.current) {
return
}
if (!document.body.contains(mountNodeRef.current)) {
mountNodeRef.current.setAttribute('data-testid', 'popover-anchor-element')
document.body.appendChild(mountNodeRef.current)
}
ReactDOM.render(component, mountNodeRef.current)
}
const closePopover = () => {
if (mountNodeRef.current) {
ReactDOM.unmountComponentAtNode(mountNodeRef.current)
}
}
return { openPopover, closePopover }
}
function App() {
const { openPopover, closePopover } = useTooltip()
return (
<div
onMouseEnter={e => {
const popoverId = 'my-popover'
const targetEl = e.currentTarget
openPopover(
<Overlay
placement="bottom"
show
target={() => targetEl}
>
<Popover id={popoverId}>Tooltip contents</Popover>
</Overlay>
)
}}
onMouseLeave={closePopover}
/>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment