Prevent multiple time submit button clicks in SPFx React based webpart.

This would be a quick tip and trick on disabling the submit button on react based SPFx webpart. Though I am showing here its usage in SPFx webpart but this can work in any React based project.

Scenario – As soon as the button is clicked, disable button immediately and then enable again once we are done without logic.

Step 1 – Add a state variable savedisabled of type boolean

 

export interface IReactGetItemsState {
 savedisabled:boolean;  
}

Step 2 – Initialize this variable with false in your react component constructor.

Step 3 – Below should be your button html.

<button disabled={this.state.savedisabled} onClick={() => this.SubmitClicked()} type="submit" name="action">
                       {this.state.savedisabled ? 'Please wait...' : 'Submit'}
                    </button>

Note here we have added below attributes

disabled={this.state.savedisabled}

and for button text what we are doing here is that is state of savedisabled is true, we will change button text to ‘Please wait..’

{this.state.savedisabled ? ‘Please wait…’ : ‘Submit’}

Step 4 – Our button click event.

 private SubmitClicked(): void {

    if (this.state.savedisabled) {
      return;
  }

    this.setState({savedisabled:true});
// below code is only to demostrate purpose in my case, it should be diffrent. 
// idea here is to set state savedisable to false when our code exeuction is done 
    sp.web.lists.getByTitle("MyList").items.add({
      Title: "Testing"
    }).then((response: ItemAddResult) => {
     
        //show success message
        this.setState({savedisabled:false});
    
    });

}

Hope this helps…Please leave a comment if you are facing any issue. Happy coding..!!!

(Visited 2,614 times, 1 visits today)