boblauer / react-onclickout

An ES6-friendly on-click-outside React component.
MIT License
92 stars 14 forks source link

Error when having `onClickOut` handler call a method of the caller component #14

Closed phalkunz closed 7 years ago

phalkunz commented 7 years ago

Please refer to this http://jsfiddle.net/3o9bobo0/

One question, why do we need setTimeout at all?

boblauer commented 7 years ago

The problem with that fiddle is not related to this component. It can be fixed by doing:

const ClickOutHandler = module.exports;

class Test extends React.Component {
  constructor() {
    this._handleClickOut = this._handleClickOut.bind(this);
    this.doSomeCoolStuff = this.doSomeCoolStuff.bind(this);
  }

    render() {
        return (
            <div>
                <ClickOutHandler onClickOut={this._handleClickOut}>
                    <div className="green" />
                </ClickOutHandler>
            </div>
        );
    }

    _handleClickOut() {
        this.doSomeCoolStuff();
    }

    doSomeCoolStuff() {
        alert('Cool stuff goes here...');
    }
}

React.render(<Test />, document.getElementById('container'));

We use setTimeout because it's possible that a click event that caused the component to be mounted in the first place would then bubble up and trigger the onClickOut function immediately.