How can i make a menu close when it's not being hovered over on react

yotube
0

Issue

So, i have a menu that is opening when i hover over it, but i want it to close when my mouse is outside the menu or the sub-menu items (i got it to close when hovering away from the menu, but then it closes before i can actually use it). Here's the code:

import React from 'react'
import styles from './Dropdown.module.css'

const Dropdown = ({children, className, style, value }) => {
const [active, setActive] = React.useState(false)
const [i, setI] = React.useState()
const anchorRef = React.useRef()

React.useEffect(() => {
anchorRef.current.removeAttribute('href')
},[])

React.useEffect(() => {
if (active) {
setI(styles.active)
}else{
setI(null)
}
},[active])

const stylesDropdown = [styles.li, className]

//the function
function handleActive() {
setActive(!active)

}

return <li className={stylesDropdown.join(' ')} style={style}
//when it's being called
onMouseOver={handleActive} >
<a href='/' className={styles.a} ref={anchorRef}>{value}</a>
<span className={styles.span}>
<i className={`fa-solid fa-sort-down ${i}`}></i>
</span>
<ul className={styles.ul}>
{active && children}
</ul>
</li>


}

export default Dropdown

Solution

nvm, solved it. i changed the function from !active to true and on the end of the ul i used this onMouseLeave ={() => setActive(false)



Answered By - Ricardo Finkelstein

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top