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!