ReactJs: Prevent multiple times button press
What you could do is make the button disabled after is clicked and leave it in the page (not clickable element).
To achieve this you have to add a ref to the button element
<button ref="btn" onClick={this.onClickUploadFile}>Send</button>
and then on the onClickUploadFile function disable the button
this.refs.btn.setAttribute("disabled", "disabled");
You can then style the disabled button accordingly to give some feedback to the user with
.btn:disabled{ /* styles go here */}
If needed make sure to reenable it with
this.refs.btn.removeAttribute("disabled");
Update: the preferred way of handling refs in React is with a function and not a string.
<button
ref={btn => { this.btn = btn; }}
onClick={this.onClickUploadFile}
>Send</button>
this.btn.setAttribute("disabled", "disabled");
this.btn.removeAttribute("disabled");
Update: Using react hooks
import {useRef} from 'react';
let btnRef = useRef();
const onBtnClick = e => {
if(btnRef.current){
btnRef.current.setAttribute("disabled", "disabled");
}
}
<button ref={btnRef} onClick={onBtnClick}>Send</button>
here is a small example using the code you provided
https://jsfiddle.net/69z2wepo/30824/
Stop a button/function from triggering when pressing enter multiple times in Reactjs
I actually found an alternative solution, which is to remove the focus of the inputs after Enter was hit:
login(elFocused) {
if(elFocused) {
elFocused = "." + elFocused;
document.querySelector(elFocused).blur();
}
}
<input onEnter={() => this.login("inputClassName")} />
This way I don't have to worry anymore for multiple Enter key hits as it is not possible anymore ;)
This is also working for the button!
Related Topics
Is Performing a Mapping Operation Without Using Returned Value an Antipattern
$.Each() VS For() Loop - and Performance
Selecting Multiple Classes with Jquery
Microsecond Timing in JavaScript
Dynamic Variables Names in JavaScript
Why JavaScript Function Declaration (And Expression)
How to Detect Timeout on an Ajax (Xmlhttprequest) Call in the Browser
Using Await Outside of an Async Function
Package.JSON' Is Not Under 'Rootdir'
Javascript/Jquery: Set Values (Selection) in a Multiple Select
Advanced JavaScript: Why Is This Function Wrapped in Parentheses
How to Disable Right-Click Context-Menu in JavaScript
Script438: Object Doesn't Support Property or Method Ie
Switch Statement for String Matching in JavaScript
Fetching Values from Email in Protractor Test Case
How Not to Forget Using Await Everywhere in JavaScript