Skip to content

Instantly share code, notes, and snippets.

@notrab
Last active March 19, 2018 11:28
Show Gist options
  • Select an option

  • Save notrab/cd499cdf129ec76060093d07a7bdf88a to your computer and use it in GitHub Desktop.

Select an option

Save notrab/cd499cdf129ec76060093d07a7bdf88a to your computer and use it in GitHub Desktop.
<Dropdown>
<DropdownItem to="/projects">My Projects</DropdownItem>
<DropdownItem to="/projects">Edit Profile</DropdownItem>
<DropdownItem to="/projects">Logout</DropdownItem>
</Dropdown>
import React, { Component } from 'react'
import styled, { keyframes } from 'styled-components'
import { Link } from 'react-router'
const fadeInDown = keyframes`
from {
opacity: 0;
transform: translateY(-5px);
}
to {
opacity: 1;
transform: translateY(0px);
}
`
const Container = styled.div`
background: #FFFFFF;
border: 1px solid #E9ECF0;
box-shadow: 0 0 15px 0 rgba(171,179,183,0.31);
border-radius: 8px;
padding: 15px;
width: 160px;
margin: 15px auto 0;
position: relative;
display: none;
animation: ${fadeInDown} 0.1s linear;
display: ${props => props.open ? 'block' : 'none'};
&:after {
position: absolute;
left: 50%;
top: -15px;
margin-left: -15px;
width: 0;
height: 0;
content: '';
border-left: 15px solid transparent;
border-right: 15px solid transparent;
border-bottom: 15px solid rgb(255, 255, 255);
filter: drop-shadow(0 1px 15px rgba(171,179,183,0.31));
z-index: 1;
}
`
export const DropdownItem = styled(Link)`
color: rgba(68, 70, 76, 1);
margin-bottom: 5px;
padding: 10px 5px;
display: block;
&:hover {
background-color: rgba(235, 100, 39, 0.1);
color: rgba(235, 100, 39, 1);
border-radius: 8px;
cursor: pointer;
}
&:last-child {
margin-bottom: 0;
}
`
export default class Dropdown extends Component {
constructor(props) {
super(props);
this.state = {
isOpen: true
}
}
toggle = (e) => {
this.setState({
isOpen: !this.state.isOpen
});
}
collapse = (e) => {
const { container } = this.refs;
const { target } = event;
if (!container.contains(target)) {
this.setState({
isOpen: false
});
}
}
componentDidMount() {
document.body.addEventListener('click', this.collapse);
}
componentWillUnmount() {
document.body.removeEventListener('click', this.collapse);
}
render() {
const { isOpen } = this.state;
const { children } = this.props;
return (
<div ref="container" tabIndex={0}>
<button onClick={this.toggle}>Button</button>
<Container open={isOpen} onBlur={this.collapse}>
{children}
</Container>
</div>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment