Home > Blockchain >  My function is getting malfunctioned after I added UseEffect
My function is getting malfunctioned after I added UseEffect

Time:10-23

I have a dropdown menu that is supposed to open and close when I click on "dropbtn". It is working perfectly but when I add Use effect so that it also closes when somebody clicks anywhere on the screen but after adding useeffect the dropdown menu is not getting closed when I click on "dropbtn". Here is the code:-

import React, { useState, useEffect } from "react";
export default function App() {
  const [listopen, setListopen] = useState(false)
  let Dropdown = () => {
    if (listopen) {
      setListopen(false)

    } else {
      setListopen(true)

    }
  }
  // Close the dropdown if the user clicks outside of it
  useEffect(() => {
    if (listopen) {
      document.addEventListener("mousedown", () => {
        setListopen(false)
      })
    }
  })
  return (
    <main>
      <header>

        <nav>
          <ul>
            <div >
              <li><button  onClick={() => Dropdown()}  >USD
                <i ></i>
              </button></li>
              <div  id="myDropdown" style={{ display: listopen === false ? 'none' : 'block' }}>
                <a href="/">Link 1</a>
                <a href="/">Link 2</a>
                <a href="/">Link 3</a>
              </div>
            </div>
          </ul>

        </nav>
      </header>
    </main>
  )
}

CodePudding user response:

Any global event listener should register only one time and should unregistered when you don't need it.

In your case event should listen when you will mount your component and must remove listener when unmount:

useEffect(() => {
  const mousedown = () => {
    setListopen(false)
  };
  document.addEventListener("mousedown", mousedown)

  // unregister mousedown event when unmount
  return () => {
    document.removeEventListener("mousedown", mousedown);
  }
}, [])

In your code useEffect will run on every change, which is reason your code not working.

CodePudding user response:

Using useEffect for your case that is closing on click outside is incorrect you should remove that and use this answer Detect click outside React component

CodePudding user response:

The reason it si not working is because you have not passed any dependency in the useEffect which is why everytime you click on button which calls Dropdown, the state gets updated as expected BUT it causes the code inside the useEffect to run again since state has changed and you have not passed any dependency. You can refer to Detect click outside React component

  • Related