Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ridewn's avatar

Toggle dropdown menu in reactjs

I have the following code for a simple dropdown menu on my navbar:

index.html

<div id="menu-button"></div>

NavMenu.js

var NavMenu = React.createClass({
    getDefaultProps: function()
    {
        return {
            isOpen: false
        };
    },

    render: function()
    {
        if (this.props.isOpen === true)
        {
            return (
                <div className="dropdown">
                    <ul>
                        <li><a href="#">News</a></li>
                        <li><a href="#">About</a></li>
                        <li><a href="#">Guidelines</a></li>
                        <li><a href="#">Exchange</a></li>
                        <li><a href="#">Forum</a></li>
                    </ul>
                </div>
            );
        }
        return null;
    }
});

NavMenuButton.js

var NavMenuButton = React.createClass({

    getInitialState: function()
    {
        return {
            isOpen: false
        };
    },

    handleClick: function(e)
    {
        e.preventDefault();
        this.setState({isOpen: !this.state.isOpen});
    },

    componentDidMount: function ()
    {
        document.body.addEventListener('click', this.handleBodyClick);
    },

    componentWillUnmount: function ()
    {
        document.body.removeEventListener('click', this.handleBodyClick);
    },

    handleBodyClick: function()
    {
        this.setState({isOpen: false});
    },

    render: function()
    {
        return (
            <div>
                <a onClick={this.handleClick} href="#">Menu</a>
                <NavMenu isOpen={this.state.isOpen} />
            </div>
        );
    }

});

React.render(<NavMenuButton />, document.getElementById('menu-button'));

I'd like the NavMenu to disappear when a user either 1. clicks the body or anywhere outside the document, and/or 2. clicks the NavMenuButton again. How can I accomplish this? Preferably with no mixins or external js files.

Clearly the problem is that if I click on the menu button to try to toggle the dropdown the handleBodyClick method is called before the handleClick method, so it sets the dropdown's state to false and then instantly sets it back to true again.

Does anyone have a different approach or recommendations on how to fix this?

Thanks!

0 likes
1 reply
Gaus's avatar

You want menu link should work as a toggle. right you need to few modifications inside code.

'''

'''

where you are passing isOpen state to another component. keep it into a div and assign an id "nav" because it will work as a separate body from the menu link. then capture the event in Componentdidmount through this nav id rather than by document.body.. Thanks!

1 like

Please or to participate in this conversation.