javascript - How to close Modal the React way? -
i have modal button , when press modal shows up. want closed if click - outside - modal-box
, regardless if click outside or inside modal-box
modal closes down. how make modal box close when pressed outside modal-box
react way?
https://codepen.io/anon/pen/mvvjor
class app extends react.component { constructor(){ super() this.state = { show: false } } openmodal() { this.setstate( prevstate => ( {show: !prevstate.show})) } closemodal() { this.setstate({show: false}) } render() { return ( <div> <button id='button' onclick={() => this.openmodal()}>the modal button</button> {this.state.show && <div id='modal' onclick={() => this.closemodal()}> <div classname="modal-box"> <h1> i'm awesome modal! </h1> </div> </div>} </div> ) } } reactdom.render(<app />, document.getelementbyid('root'))
#modal { display: block; position: fixed; padding-top: 50px; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0 ,0 ,0 , 0.5); } .modal-box { z-index: 50; margin: auto; width: 80%; height: 200px; background-color: white; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>
class app extends react.component { constructor(){ super() this.state = { show: false } } openmodal() { this.setstate( prevstate => ( {show: !prevstate.show})) } closemodal(e) { if(e.target.id === "modal") { this.setstate({show: false}) } } render() { return ( <div> <button id='button' onclick={() => this.openmodal()}>the modal button</button> {this.state.show && <div id='modal' onclick={(e) => this.closemodal(e)}> <div classname="modal-box"> <h1> i'm awesome modal! </h1> </div> </div>} </div> ) } } reactdom.render(<app />, document.getelementbyid('root'))
here's demo - https://codepen.io/anon/pen/dzmpqv
Comments
Post a Comment