Freewind
Freewind

Reputation: 198238

Why the ref button will be clicked 3 times?

I have a very simple react component:

import React, {Component} from 'react';

class Hello extends Component {
  render() {
    return <div>
      <h1>Hello Freewind</h1>
      <div>
        <button ref="button1" onClick={() => alert('1')}>Click 1</button>
        <button ref="button2" onClick={() => alert('2')}>Click 2</button>
      </div>
      <div>
        <button onClick={this._clickBoth.bind(this)}>Click both</button>
      </div>
    </div>;
  }

  _clickBoth() {
    this.refs.button1.click();
    this.refs.button2.click();
  }
}

export default Hello;

When you click on the "Click both" button, the "Click 1" and "Click 2" button will be clicked programatically. The strange thing is, I will see 6 alerts:

1
2
1
2
1
2

Which should be

1
2

But if I remove either line of _clickBoth, say, remove this.refs.button2.click();, it will behaive correctly and only show one alert:

1

You can see and try the project here: https://github.com/js-demos/react-ref-demo

Upvotes: 8

Views: 171

Answers (2)

mflodin
mflodin

Reputation: 1113

Also not sure what is going on, but I added a console.log to the _clickBoth handler and got the following result:

click both
click both
click both
1
2
1
click both
click both
2
1
2

Upvotes: 0

Cosmin Ababei
Cosmin Ababei

Reputation: 7072

I'm not sure what's wrong, but I'd definitely like to find out the technicalities behind it.

In the meantime, if you're looking for a way to fix it, you can wrap the buttons' click inside setTimeout, like this:

setTimeout(() => {
  this.refs.button1.click();
  this.refs.button2.click();
}, 0);

Upvotes: 1

Related Questions