Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to close a dropdown when launching another dropdown #11

Open
drclohite opened this issue May 30, 2020 · 2 comments
Open

how to close a dropdown when launching another dropdown #11

drclohite opened this issue May 30, 2020 · 2 comments

Comments

@drclohite
Copy link

Navbar includes multiple NavItems, they could include multiple dropdowns - it all works very well thank you. If I have one drop-down great. However, if I have a second drop-down menu it does not close the first when I open a new one which then appears underneath the first drop-down which is not the desired action. So it is both nonfunctional and looks bad.

An answer to this question could help people to work out how to resolve the other issue which could then be resolved with 'react-onclickoutside' maybe

@Jake-Breaks-Stuff
Copy link

Jake-Breaks-Stuff commented Jun 24, 2020

I had a similar issue with two dropdowns side by side on the navbar.
I'd solved it with the following by modifying the NatItem() function, and adding useRef to the import list.

function NavItem(props) {
    const [open, setOpen] = useState(false);
    const node = useRef();
    //Mounts the mouse handler check
    //If a click outside the dropdown occurs, it closes the dropdown.
    useEffect(() => {
        //add when mounted
        document.addEventListener("mousedown", handleClick);
        return () => {
            document.removeEventListener("mousedown", handleClick);
        };
    }, []);

    const handleClick = (e) => {
        if (node.current.contains(e.target)) {
            //inside element click, returns no change
            return;
        }
        //if clicked outside, forces the drop down to close.
        setOpen(false);
    };

    return (
        <li className="nav-item" ref={node}>
            <a href="#" className="icon-button" onClick={() => setOpen(!open)}>
                {props.icon}
            </a>

            {open && props.children}
        </li>
    );
}

Then within the NavItem() return statement, I added a reference to

Hope this helps!

@ouda21
Copy link

ouda21 commented Oct 31, 2020

@Jake-Breaks-Stuff nicely done buddy. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants