<!DOCTYPE html>
<html>
<head>
<script data-require="react@*" data-semver="15.2.0" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.0/react.min.js"></script>
<script data-require="react@*" data-semver="15.2.0" src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.0/react-dom.min.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="root"></div>
<script src="menu.js"></script>
<script src="script.js"></script>
</body>
</html>
class Menu extends React.Component {
constructor(props) {
super(props)
this.state = {
isVisible: false
}
this.handleClickOutside = this.handleClickOutside.bind(this)
this.toggleOptions = this.toggleOptions.bind(this)
this.handleClick = this.handleClick.bind(this)
}
componentDidMount() {
document.addEventListener('click', this.handleClickOutside)
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClickOutside)
}
handleClickOutside(evt) {
if (!this.node.contains(evt.target)) {
this.setState({ isVisible: false })
}
}
toggleOptions(evt) {
evt.preventDefault()
this.setState(state => ({ isVisible: !state.isVisible }))
}
handleClick(choice, evt) {
evt.preventDefault()
this.props.handleMenuChoice(choice)
this.setState({ isVisible: false })
}
render() {
return (
<div className="menu" ref={el => (this.node = el)}>
<a href="#" onClick={this.toggleOptions}>
Options
</a>
{this.state.isVisible
? <div className="menuContents">
<a href="#" onClick={this.handleClick.bind(null, 'one')}>
One
</a>
<a href="#" onClick={this.handleClick.bind(null, 'two')}>
Two
</a>
<a href="#" onClick={this.handleClick.bind(null, 'three')}>
Three
</a>
<a href="#" onClick={this.handleClick.bind(null, '')}>
Clear Selection
</a>
</div>
: null}
</div>
)
}
}
body {
font-family: sans-serif;
}
a {
display: block;
color: #1520f2;
text-decoration: none;
font-weight: bold;
font-size: 20px;
}
a:hover {
text-decoration: underline;
}
.menu {
width: 100px;
}
.menuContents {
display: block;
position: absolute;
background-color: #f9f9f9;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
padding: 12px 16px;
z-index: 1;
}
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
currentChoice: ''
}
this.handleChoice = this.handleChoice.bind(this)
}
handleChoice(choice) {
this.setState({ currentChoice: choice })
}
render() {
return (
<div>
<Menu handleMenuChoice={this.handleChoice} />
<div>
<h1>
{this.state.currentChoice || 'No Selection Made'}
</h1>
</div>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'))