index.js (706B)
1 import { h, Component } from 'preact'; 2 3 export default class ClickOutside extends Component { 4 handleClick = (ev) => { 5 if (!this.elRef.contains(ev.target)) { 6 this.props.action(); 7 } 8 } 9 componentDidMount() { 10 // setTimeout ensures the click event doesn't get triggered while mounting 11 window.setTimeout(() => { 12 document.addEventListener('click', this.handleClick); 13 }, 0); 14 } 15 componentWillUnmount() { 16 document.removeEventListener('click', this.handleClick); 17 } 18 render() { 19 return ( 20 <div ref={ref => {this.elRef = ref}}> 21 {this.props.children} 22 </div> 23 ); 24 } 25 }