S
S
Sergey2020-11-20 10:35:52
React
Sergey, 2020-11-20 10:35:52

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

1 answer(s)
M
Maxim, 2020-11-25
@4elentano551

You need to create an entity that knows about all the tooltips. When clicking on "closed", notify this place, and push new values ​​(isOpen) to all tooltips

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question