Pomax / react-onclickoutside

An onClickOutside wrapper for React components

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to use two or more instance?

Mirkadoi opened this issue · comments

How can are use two or more instance component? If you use the component more than once, then the outsider click does not work. Only on the last component. And it works weird. If this is not a bug, then is it possible to solve the problem? Thank.

example problems:
https://codesandbox.io/s/yw45z06749?fontsize=14

commented

Functional components have no public API. So there is literally no way for this kind of code to work: you it can't call the outside click handler on "the component instance" because it has no way of knowing what that instance even is. All it can see is your Menu const, of which there is only one, and which instance that points to is undefined (apparently, it points to the last rendered one, but that's undefined behaviour and relying on that to always be the case is a recipe for bugs).

You'll have to use a regular class, which is hardly more code in this case:

import React, { Component } from "react";
import "./Menu.css";
import onClickOutside from "react-onclickoutside";

const uuid = (() => { let id = 1; return () => id++; })();

class Menu extends Component {
  constructor(props) {
    super(props);
    this.state = { isOpen: false };
    this.id = uuid();
  }
  
  toggle() {
    this.setState({ isOpen: !this.state.isOpen });
  }

  handleClickOutside() {
    this.setState({ isOpen: false });
  }
  
  render() {
    return (
      <li className={this.state.isOpen ? "m-menu -active" : "m-menu "} onClick={() => this.toggle()}>
        <div> Open Menu </div>
        <ul className="m-menu__list">
          <li className="m-menu__item">
            <div className="m-menu__link">Log Out {this.id}</div>
          </li>
        </ul>
      </li>
    );
  }
};

export default onClickOutside(Menu);

Functional components are great for "render and forget" parts of your UI. For things that require talking to, which this HoC very much needs to do, functional components are no bueno.