@mongodb-js/mongodb-ui-components
Version:
A collection of frequently used functional UI components found on mongodb properties
82 lines (68 loc) • 2.16 kB
JavaScript
'use strict';
const React = require('react');
const style = require('../shared/style');
const dropdownStyle = require('./style');
class Dropdown extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
isOpen: false,
activeIndex: this.props.activeIndex || 0,
hoverIndex: 0
};
this.onOptionClick = this.onOptionClick.bind(this);
this.onOptionEnter = this.onOptionEnter.bind(this);
}
componentDidMount() {
style('dropdown', dropdownStyle(this.props.options.length * 40));
}
componentWillReceiveProps(newProps) {
if (newProps.activeIndex !== undefined) {
this.setState({ activeIndex: newProps.activeIndex });
}
}
onOptionClick(e) {
if (!this.state.isOpen) {
return this.setState({ isOpen: true });
}
const i = Number(e.currentTarget.getAttribute('data-i'));
this.setState({ hoverIndex: 0, activeIndex: i, isOpen: false });
this.props.onSelect(i);
}
onOptionEnter(e) {
if (!this.state.isOpen) return;
const i = Number(e.currentTarget.getAttribute('data-i'));
if (i !== this.state.hoverIndex) {
this.setState({ hoverIndex: i });
}
}
render() {
return React.createElement(
'div',
{ className: 'dropdown__container' },
React.createElement(
'div',
{ className: `dropdown ${this.state.isOpen ? 'dropdown--open' : ''}` },
React.createElement('div', { className: 'dropdown__arrow', style: this.state.isOpen ? {
transform: `translateY(${this.state.hoverIndex * 40}px) rotateZ(90deg)`
} : {} }),
this.props.options.map((option, i) => {
return React.createElement(
'div',
{
key: i,
'data-i': i,
className: 'dropdown__option',
style: {
transform: this.state.isOpen ? 'translateY(0)' : `translateY(${-this.state.activeIndex * 40}px)`
},
onClick: this.onOptionClick,
onMouseEnter: this.onOptionEnter },
option
);
})
)
);
}
}
module.exports = Dropdown;