Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the ref button will be clicked 3 times?

Tags:

reactjs

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

like image 209
Freewind Avatar asked Aug 23 '16 06:08

Freewind


1 Answers

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);
like image 105
Cosmin Ababei Avatar answered Oct 01 '22 03:10

Cosmin Ababei