简体   繁体   中英

Menu not opening when clicking on react-icons icon

I have a menu that should open when I click on a button. and close when I click the button again or click outside the menu. It works right but it has a bug when I click on svg icon inside button, and it does not work, the menu does not open.

 const MoreActionBtn = () => {
  const [showMoreAction, setShowMoreAction] = useState(false);
  const moreBtns = useRef();
  const { current } = moreBtns;

  useEffect(() => {
    const outSideClickHandler = (e) => {
      if (current && !current.contains(e.target)) {
        setShowMoreAction(false);
      }
    };
    document.addEventListener("click", outSideClickHandler);
    return () => {
      document.removeEventListener("click", outSideClickHandler);
    };
  }, [current]);

  function toggleMoreAcrion() {
    setShowMoreAction((prev) => !prev);
  }

  return (
    <div ref={moreBtns} className="more-action-wrapper">
      {showMoreAction && (
        <div>
          <button>
            <MdDone />
          </button>
          <button>
            <MdOutlineModeEdit />
          </button>
        </div>
      )}
      <button onClick={toggleMoreAcrion}>
        {showMoreAction ? <MdOutlineCancel /> : <MdStars />}
      </button>
    </div>
  );
};

Here is a codesandbox of my code. Is there a better solution?

It seems like the problem is simpler than I thought. What's happening is that somehow the svg rendered by MdStar from react-icons is catching the click. To avoid this add the below CSS:

.more-action-wrapper svg {
  pointer-events: none;
}

Working forked of your CodeSandbox here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM