import React, { Component } from 'react' import PropTypes from "prop-types"; import './Dropdown.css' class Dropdown extends Component { state = { open: false } renderList = () => { const { list, align } = this.props if (!this.state.open) { return null } return (
{ list.map(({ icon, title, link, onClick }, key) => ( this.handleOnClick(onClick)} > {icon && } {title} )) }
) } handleOnClick = (onClick) => { this.toggleList() if (onClick) { onClick() } } handleMouseClick = (e) => { if (this.node.contains(e.target)) { return } this.toggleList() } renderTitleElement = () => { const { titleElement, title } = this.props if (titleElement) return titleElement return ( <> {title} ) } toggleList = () => { const { open } = this.state let state = true document.addEventListener('mousedown', this.handleMouseClick, false) if (open) { document.removeEventListener('mousedown', this.handleMouseClick, false) state = false } this.setState({ open: state }) } render() { return (
this.node = node}>
{this.renderTitleElement()}
{this.renderList()}
) } } Dropdown.propTypes = { titleElement: PropTypes.node, align: PropTypes.oneOf(['left', 'center', 'right']), list: PropTypes.arrayOf(PropTypes.shape({ title: PropTypes.string.isRequired, icon: PropTypes.string, onClick: PropTypes.func, link: PropTypes.string, })) }; export default Dropdown