Answer the question
In order to leave comments, you need to log in
How to close all open tooltips when clicking on a closed one in React?
There is a working code to open the tooltip. But how to close all open ones when clicking on the closed one? I would like to do without third-party packages.
import React from "react";
import cn from "classnames";
class Tooltip extends React.Component {
constructor() {
super();
this.state = {
isOpen: false,
topOffset: 0,
}
}
openTooltip(e) {
const {target} = e;
const targetTopOffset = target.getBoundingClientRect().top;
if (target.classList.contains('--is-open')) {
setTimeout(() => {
this.closeTooltip();
}, 100);
}
this.setState({
isOpen: true,
});
this.setState({
topOffset: targetTopOffset + 30,
});
window.addEventListener('scroll', () => {
this.closeTooltip();
})
}
closeTooltip() {
this.setState({
isOpen: false,
topOffset: 0,
});
}
render() {
const styles = {
top: this.state.topOffset + 'px'
}
return (
<div className={cn(
'tooltip',
this.props.extraClass,
)}>
<button
className={cn(
'tooltip__label',
{'--is-open': this.state.isOpen}
)}
onClick={this.openTooltip.bind(this)}
>
{this.props.label || '?'}
</button>
<span className="tooltip__content" style={styles}>
{this.props.children}
</span>
</div>
);
}
}
export default Tooltip;
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question