JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.1/react-dom.min.js"></script>
CSS
body {
background-color: #f0f0f0;
}
button {
background: #34495e;
border: 0;
color: #fff;
display: block;
width: 100%;
margin: 0 auto 20px;
border-radius: 4px;
padding: 0;
line-height: 40px;
}
.popover {
background: #fff;
border-radius: 4px;
width: 300px;
margin: 20px auto;
padding: 15px;
position: absolute;
top: 100%;
left: -50px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
.popover-container {
width: 200px;
margin: 50px auto;
position: relative;
}
.clickME{
background: green
}
}
Babel + JSX
class Popover extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
this.handleOutsideClick = this.handleOutsideClick.bind(this);
this.state = {
popupVisible: false,
element: true,
};
}
handleClick() {
if (!this.state.popupVisible) {
// attach/remove event handler
document.addEventListener('click', this.handleOutsideClick, false);
} else {
document.removeEventListener('click', this.handleOutsideClick, false);
}
this.setState(prevState => ({
popupVisible: !prevState.popupVisible,
}));
}
handleOutsideClick(e) {
// ignore clicks on the component itself
if (this.node.contains(e.target)) {
return;
}
this.handleClick();
}
returnElement(){
if(!!this.state.element){
return (<p className='clickME' onClick={()=>this.setState({element:false})}>click me</p>)
}
}
render() {
return (
<div className="popover-container" ref={node => { this.node = node; }}>
<button
onClick={this.handleClick}
>
Toggle Popover
</button>
{this.state.popupVisible && (
<div
className="popover"
>
{this.returnElement()}
I'm a popover!
</div>
)}
</div>
);
}
}
ReactDOM.render(<Popover />, document.body);