Tooltip to react portal to fix in overflow elements

This commit is contained in:
mrfry 2021-05-31 19:15:16 +02:00
parent b52d72b909
commit d6e0cbdbd3
3 changed files with 34 additions and 12 deletions

View file

@ -1,11 +1,36 @@
import React from 'react'
import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import styles from './tooltip.module.css'
export default function Tooltip({ children, text, opened }) {
const defWidth = 300
const defHeight = 250
export default function Tooltip({ children, text, opened, width, height }) {
const [ref, setRef] = useState(React.createRef()) // eslint-disable-line
const rect = ref.current ? ref.current.getBoundingClientRect() : null
const h = height || defHeight // eslint-disable-line
const w = width || defWidth // eslint-disable-line
return (
<span className={styles.tooltip}>
<span className={styles.tooltip} ref={ref}>
{text && text()}
{opened && <span className={styles.tooltiptext}>{children}</span>}
{opened &&
ReactDOM.createPortal(
<span
style={{
width: `${w}px`,
maxWidth: `${w}px`,
height: `${h}px`,
maxHeight: `${h}px`,
top: rect ? rect.top - h - 15 + window.scrollY : 0,
left: rect ? rect.left + window.scrollX : 0,
}}
className={styles.tooltiptext}
>
{children}
</span>,
document.body
)}
</span>
)
}