Created
February 21, 2019 15:46
-
-
Save tonysaffo/af5363e85294826738f147f770fa8596 to your computer and use it in GitHub Desktop.
UserInfo component with detection of outside clicking
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react' | |
import { Link } from 'react-router-dom' | |
import { connect } from 'react-redux' | |
import './userInfo.scss' | |
class UserInfo extends Component { | |
constructor(props) { | |
super(props); | |
this.setWrapperRef = this.setWrapperRef.bind(this); | |
this.handleClickOutside = this.handleClickOutside.bind(this); | |
} | |
componentDidMount() { | |
document.addEventListener('mousedown', this.handleClickOutside); | |
} | |
componentWillUnmount() { | |
document.removeEventListener('mousedown', this.handleClickOutside); | |
} | |
/** | |
* Set the wrapper ref | |
*/ | |
setWrapperRef(node) { | |
this.wrapperRef = node; | |
} | |
/** | |
* Alert if clicked on outside of element | |
*/ | |
handleClickOutside(event) { | |
if (this.wrapperRef && !this.wrapperRef.contains(event.target)) { | |
this.hideHiddenMenu() | |
} | |
} | |
state = { | |
showHiddenMenu: false | |
} | |
toggleHiddenMenu = () => { | |
this.setState({ showHiddenMenu: !this.state.showHiddenMenu }) | |
} | |
hideHiddenMenu = () => { | |
this.setState({ showHiddenMenu: false }) | |
} | |
render() { | |
const { currentUser } = this.props | |
return ( | |
<div className='user-info' ref={this.setWrapperRef}> | |
<div className="img" style={{ backgroundImage: `url(${currentUser.photoURL})` }}></div> | |
<div className="username">{ currentUser.displayName }</div> | |
<div className="icon" onClick={this.toggleHiddenMenu}><i className="fa fa-list" aria-hidden="true"></i></div> | |
{this.state.showHiddenMenu ? <HiddenMenu/> : null} | |
</div> | |
) | |
} | |
} | |
const HiddenMenu = () => { | |
return ( | |
<div className='hidden-menu'> | |
<Link to='/profile'>Profile</Link> | |
<div className="line"></div> | |
<Link to='/chunks'>Chunks</Link> | |
<Link to='/tags'>Tags</Link> | |
<div className="line"></div> | |
<div className="logout"> | |
<span>Logout</span> | |
<i className="fa fa-sign-out" aria-hidden="true"></i> | |
</div> | |
</div> | |
) | |
} | |
const mapStateToProps = state => ({ | |
currentUser: state.user.currentUser | |
}) | |
export default connect(mapStateToProps)(UserInfo) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment