How to close all open tooltips when clicking on a closed one in React?

  • 0
    There is a working code for opening a tooltip. But how to close all open ones when you click on a closed one? I would like to do it 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;
    React Nathaniel Fox, Nov 26, 2020

  • 1 Answers
  • 0
    You need to create an entity that will know about all tooltips. When you click on "closed", notify this place, and throw new values ​​(isOpen) into all tooltips
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!