Skip to content

Instantly share code, notes, and snippets.

@ferrannp
Last active June 23, 2017 14:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ferrannp/0e14c4f43d776e09a4e262364f8e3508 to your computer and use it in GitHub Desktop.
Save ferrannp/0e14c4f43d776e09a4e262364f8e3508 to your computer and use it in GitHub Desktop.
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