Last active
June 23, 2017 14:10
-
-
Save ferrannp/0e14c4f43d776e09a4e262364f8e3508 to your computer and use it in GitHub Desktop.
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
const EnhanceDropdown = ComposedComponent => class extends Component { | |
constructor() { | |
super(); | |
this.state = { isOpen: false }; | |
this.onToggle = this.onToggle.bind(this); | |
this.handleDocumentClick = this.handleDocumentClick.bind(this); | |
this.onSelect = this.onSelect.bind(this); | |
} | |
componentDidMount() { | |
window.addEventListener('click', this.handleDocumentClick) | |
} | |
componentWillUnmount () { | |
window.removeEventListener('click', this.handleDocumentClick) | |
} | |
handleDocumentClick() { | |
if(this.state.isOpen) { | |
this.onToggle(); | |
} | |
} | |
onToggle() { | |
this.setState({ isOpen: !this.state.isOpen }); | |
} | |
onSelect(option) { | |
this.onToggle(); // Close dropdown | |
// Call parent callback or maybe a Redux/Flux action? | |
if(this.props.onSelect) this.props.onSelect(option); | |
} | |
render() { | |
return ( | |
<div onClick={(e) => e.stopPropagation()}> | |
<ComposedComponent {...this.props} | |
onToggle={this.onToggle} | |
onSelect={this.onSelect} | |
isOpen={this.state.isOpen} | |
optionSelected={this.props.optionSelected} | |
data={this.props.data} | |
/> | |
</div> | |
); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment