Sebastian Olsen Sebastian Olsen - 1 year ago 95
Javascript Question

this.setState() not working properly with bound events

I'm making an easily toggleable component, here I've made a door as an example. You click the door and it opens, if you click on it again, it closes. If you click outside of the door, it will close as well.

My issue here is that in the

method, the
is always
, no matter what. Even after I set the state, it returns false when I
it. The actual
does get the
class assigned to it though, so why does the method not see the change?

export default class Door extends React.Component {
constructor() {
this.state = {
active: false,

this.close = this.close.bind(this) =

handleClick() {
if ( == false) {
} else {

open() {
document.body.addEventListener('click', this.close, true)
this.setState({active: true})

close() {
document.body.removeEventListener('click', this.close, true)
this.setState({active: false})

render() {

let classes = {
active: ? 'active ' : '',

return (
<div onClick={this.handleClick.bind(this)} className={"door " +}>

Answer Source

You should stop propagation:

handleClick(e) {
    if ( == false) {
    } else {

When you are trying to close the door, the handleClick is called twice. once by the div click, and then by the body click. This can be avoided by stopping the event from bubbling up when handled once.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download