I'm trying to develop a Tooltip component. To do so, I have to access the children (object that fires the tooltip) in order to get the events listeners.
I'm using React.cloneElement to achieve this, but the problem is this only works when the child is a DOM element, but doesn't work with functional components.
export const Tooltip = ({text, placement = 'top', space = 15, children, disabled = 0, delay = 0, ...props}) => {
const [show, setShow] = useState(0);
const handleMouseOver = () => {
setShow(1); // shows the tooltip
console.log('Mouse over');
};
const handleMouseOut = () => {
setShow(0); // hides the tooltip
console.log('Mouse out');
};
return (
<>
{ React.cloneElement(children, {
...children.props,
onMouseOver: handleMouseOver, //the events only fires if it is a DOM element
onMouseLeave: handleMouseOut,
})}
{ disabled ||
<StyledTooltip delay={delay} ref={tooltipRef} posRef={posRef} show={show}>{text}
</StyledTooltip>
}
</>
)
}
How could make it works whether the child is DOM element or functional component?
Thanks in advance!