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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With