Skip to content

dropdown not closing on clicking on same icon reactjs #26538

@RahulMittal18

Description

@RahulMittal18

Expected Behavior : When clicked on profile icon, if dropdown is not open,open the dropdown else close the dropdown. And close the dropdown if clicked anywhere outside the dropdown.

Actual Behavior: When clicked on profile icon, if dropdown is not open, the dropdown gets open. And the dropdown is also closing if clicked anywhere outside the dropdown. but if dropdown is already open, it does not close on clicking on profile icon again.

Here is my code:

const Navbar = () => {
  const [isOpen, setIsOpen] = useState(false);
  const imgRef = useRef();
  useEffect(() => {
    let closeDropdown = (e) => {
      if (imgRef.current && !imgRef.current.contains(e.target)) {
        setIsOpen(false);
      }
    };
    document.body.addEventListener("click", closeDropdown);
    return () => document.body.removeEventListener("click", closeDropdown);
    }, []);


    return (
       <div>
              <div className={"dropdownn1 " + (isOpen ? "open" : "closed")}>
                    <Dropdown />
              </div>
              <div className="profile_icon_div" ref={imgRef}>
                     <img
                        src={profileImageUrl}
                        onClick={() => setIsOpen((prev) => !prev)}
                        className="profile_icon_image"
                        alt=""
                      />
               </div>
        </div>
      );
};

export default Navbar;

Metadata

Metadata

Assignees

No one assigned

    Labels

    Resolution: StaleAutomatically closed due to inactivity

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions