简体   繁体   中英

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

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

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

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