ReactJs: Prevent multiple times button press ReactJs: Prevent multiple times button press javascript javascript

ReactJs: Prevent multiple times button press


The solution is to check the state immediately upon entry to the handler. React guarantees that setState inside interactive events (such as click) is flushed at browser event boundary. Ref: https://github.com/facebook/react/issues/11171#issuecomment-357945371

// In constructorthis.state = {    disabled : false};// Handler for on clickhandleClick = (event) => {    if (this.state.disabled) {        return;    }    this.setState({disabled: true});    // Send     }// In render<button onClick={this.handleClick} disabled={this.state.disabled} ...>    {this.state.disabled ? 'Sending...' : 'Send'}<button>


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 providedhttps://jsfiddle.net/69z2wepo/30824/


Tested as working one: http://codepen.io/zvona/pen/KVbVPQ

class UploadArea extends React.Component {  constructor(props) {    super(props)    this.state = {      isButtonDisabled: false    }  }  uploadFile() {    // first set the isButtonDisabled to true    this.setState({      isButtonDisabled: true    });    // then do your thing  }  render() {    return (      <button        type='submit'        onClick={() => this.uploadFile()}        disabled={this.state.isButtonDisabled}>        Upload      </button>    )  }}ReactDOM.render(<UploadArea />, document.body);