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 class="dropdown">
<li><button class="dropbtn" onClick={() => Dropdown()} >USD
<i class="fa fa-caret-down"></i>
</button></li>
<div class="dropdown-content" 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>
)
}