Skip to content

Instantly share code, notes, and snippets.

@juliantrueflynn
Last active July 29, 2018 17:43
Show Gist options
  • Save juliantrueflynn/d5a2156ca11b01bc8f303ff57bb08681 to your computer and use it in GitHub Desktop.
Save juliantrueflynn/d5a2156ca11b01bc8f303ff57bb08681 to your computer and use it in GitHub Desktop.
React Dropdown component using onBlur, onFocus, onMouseDown
import React from 'react';
class Dropdown extends React.Component {
constructor(props) {
super(props);
this.state = { isDropdownOpen: false };
this.handleOpen = this.handleOpen.bind(this);
this.handleClose = this.handleClose.bind(this);
this.handleDropdownClick = this.handleDropdownClick.bind(this);
this.handleTogglerClick = this.handleTogglerClick.bind(this);
}
handleOpen() {
this.setState({ isDropdownOpen: true });
}
handleClose() {
this.setState({ isDropdownOpen: false });
}
handleDropdownClick(e) {
const { isDropdownOpen } = this.state;
if (!isDropdownOpen) {
this.handleOpen();
return;
}
e.preventDefault();
e.stopPropagation();
}
handleTogglerClick() {
const { isDropdownOpen } = this.state;
this.setState({ isDropdownOpen: !isDropdownOpen });
}
render() {
const { isDropdownOpen } = this.state;
const { togglerText, children } = this.props;
return (
<div
onFocus={this.handleOpen}
onBlur={this.handleClose}
onMouseDown={this.handleDropdownClick}
tabIndex="0"
role="button"
>
<button type="button" className="btn btn__dropdown" onMouseDown={this.handleTogglerClick}>
{togglerText}
</button>
{isDropdownOpen && (
<div className="dropdown__content">
{children}
</div>
)}
</div>
);
}
}
export default Dropdown;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment