Search code examples
reactjsstatebind

Detect mouse click and change state in React


I have a div which is displayed depending upon a variable- eg: showDiv. After i set showDiv= true, div will appear.

{showDiv && <div id="someid"> text</div>}

Have set a timeout to change variable value so that div will disappear after a time (7 seconds)

thisState.setState({showDiv:true});
setTimeout(function(){
                thisState.setState({false});
            }.bind(this),7000);

How can i add a code to detect any mouse click and change variable based on that ? Requirement is that, div should disappear either 1. after 7 seconds (already done) 2. based on a click event (if user just clicks on the screen)

Any thoughts ?


Solution

  • You are looking for a window event-listener essentially.

    componentDidMount(){
        window.addEventListener("click", this.hideDiv)
    }
    
    hideDiv = () => {
        if(this.state.showDiv){
           this.setState({
              showDiv: false
           })
        }
    }
    

    Also remember to remove that listener before the component unmounts:

    componentWillUnmount{
       window.removeEventListener("click", this.hideDiv)
    }
    

    See working sandbox: https://codesandbox.io/s/stupefied-silence-snhnw