Make menu close when user clicks away

Also moved toggle button handling into Menu component to simplify
logic.
This commit is contained in:
Alex Liebowitz 2016-05-28 06:22:09 -04:00
parent 85f13d9991
commit c41c9c07c3
2 changed files with 33 additions and 20 deletions

View file

@ -36,9 +36,36 @@ var menuStyle = {
};
var Menu = React.createClass({
handleWindowClick: function(e) {
if (this.props.toggleButton && ReactDOM.findDOMNode(this.props.toggleButton).contains(e.target)) {
// Toggle button was clicked
this.setState({
open: !this.state.open
});
} else if (this.state.open && !this.refs.div.contains(e.target)) {
// Menu is open and user clicked outside of it
this.setState({
open: false
});
}
},
propTypes: {
openButton: React.PropTypes.element,
},
getInitialState: function() {
return {
open: false,
};
},
componentDidMount: function() {
window.addEventListener('click', this.handleWindowClick, false);
},
componentWillUnmount: function() {
window.removeEventListener('click', this.handleWindowClick, false);
},
render: function() {
return (
<div style={menuStyle}>
<div ref='div' style={menuStyle} className={this.state.open ? '' : 'hidden'}>
{this.props.children}
</div>
);
@ -74,7 +101,6 @@ var MenuItem = React.createClass({
}
});
var creditAmountStyle = {
color: '#216C2A',
fontWeight: 'bold',
@ -104,6 +130,7 @@ var subPageLogoStyle = {
display: 'block',
marginTop: '36px',
};
var SubPageLogo = React.createClass({
render: function() {
return <img src="img/lbry-dark-1600x528.png" style={subPageLogoStyle} />;

View file

@ -243,19 +243,11 @@ var mainMenuStyle = {
};
var MainMenu = React.createClass({
propTypes: {
show: React.PropTypes.bool,
},
getDefaultProps: function() {
return {
show: false,
}
},
render: function() {
var isLinux = /linux/i.test(navigator.userAgent); // @TODO: find a way to use getVersionInfo() here without messy state management
return (
<div style={mainMenuStyle} className={this.props.show ? '' : 'hidden'}>
<Menu>
<div style={mainMenuStyle}>
<Menu {...this.props}>
<MenuItem href='/?files' label="My Files" icon='icon-cloud-download' />
<MenuItem href='/?settings' label="Settings" icon='icon-gear' />
<MenuItem href='/?help' label="Help" icon='icon-question-circle' />
@ -271,7 +263,6 @@ var TopBar = React.createClass({
getInitialState: function() {
return {
balance: 0,
menuOpen: false,
};
},
componentDidMount: function() {
@ -284,11 +275,6 @@ var TopBar = React.createClass({
onClose: function() {
window.location.href = "?start";
},
toggleMenu: function() {
this.setState({
menuOpen: !this.state.menuOpen,
});
},
render: function() {
return (
<span className='top-bar' style={topBarStyle}>
@ -296,8 +282,8 @@ var TopBar = React.createClass({
<CreditAmount amount={this.state.balance}/>
</span>
<Link onClick={this.toggleMenu} title="Menu" icon='icon-bars' />
<MainMenu show={this.state.menuOpen} />
<Link ref="menuButton" title="LBRY Menu" icon="icon-bars" />
<MainMenu toggleButton={this.refs.menuButton} />
</span>
);
}