score:1

Accepted answer

Please find the updated code that helps to solve your issue:

import ReactDOM from "react-dom";

import "./styles.css";
import React, { Component } from "react";

class OptionsMenu extends Component {
  constructor() {
    super();
    this.dropdownBoxRef = React.createRef();
  }

  handleClickOutside = event => {
    if (this.dropdownBoxRef && !this.dropdownBoxRef.current.contains(event.target)) {
      this.props.close();
    }
  };

  componentDidMount() {
    document.addEventListener("mousedown", this.handleClickOutside);
  }

  componentWillUnmount() {
    document.removeEventListener("mousedown", this.handleClickOutside);
  }

  render() {
    const options = ["a", "b", "c"].map(option => (
      <li className="OptionsList-Element">
        <div className="OptionsList-ElementIcon">Icon</div>
        <span>{option.label}</span>
      </li>
    ));
    return (
      <div ref={this.dropdownBoxRef} styles={this.props.styles}>
        <ul className="OptionsList">{options}</ul>
      </div>
    );
  }
}

export default OptionsMenu;

const rootElement = document.getElementById("root");
ReactDOM.render(<OptionsMenu />, rootElement);

Note: this.dropdownBoxRef.current.contains(event.target) line is the game changer.

score:0

Refs have things stored inside a property called current. So in order to actually reach your element you'll have to do this.dropdownBoxRef.current and call .contains on that.


Related Query

More Query from same tag