Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I can disable a button in React js for 5 seconds after click event

Tags:

reactjs

I am new to react. I need help in disabling a button for 5 seconds in react js for my project and then re enable it back.

here is my code,

constructor (props) {
    super(props);
    this.onLaunchClicked = this.onLaunchClicked.bind(this);
    this.state = {
        isButtonDisabled: false
    }
}

onLaunchClicked (event) {
    event.preventDefault();
    this.setState({
        isButtonDisabled: true
    });
    return this.props.onLaunchClicked();

}

       render () {
    return (
        <div className="client-playtest-state">
            <button className="btn bg-success" onClick={this.onLaunchClicked} 
         disabled={this.state.isButtonDisabled}>LAUNCH</button>
        </div>
    );
}
like image 482
Bharat Singh Avatar asked May 24 '17 10:05

Bharat Singh


People also ask

How do you disable a button after click in react?

Use the disabled prop to disable a button in React, e.g. <button disabled={true}>Click</button> . You can use the prop to conditionally disable the button based on the value of an input field or another variable or to prevent multiple clicks to the button.

How do I automatically trigger a button click after 5 seconds with react?

You could create a ref for the <button> and set a timeout inside of an effect hook to call the button click event after 5 seconds. You could throw in a state hook to limit the prompt. Used setInterval instead of setTimeout to retry every 5 seconds.

How do you make button enable and disable in react JS?

By default, a button's disabled property is set to false. It means that by default, a button is active. If you want to disable a button using JavaScript, you can switch this value to true once you have created and selected the button (steps 1 and 2). // Disable a button in JavaScript button.


1 Answers

You can use setTimeout and update the state back after a timeout.

constructor (props) {
    super(props);
    this.onLaunchClicked = this.onLaunchClicked.bind(this);
    this.state = {
        isButtonDisabled: false
    }
}

onLaunchClicked (event) {
    event.preventDefault();
    this.setState({
        isButtonDisabled: true
    });

    // **** here's the timeout ****
    setTimeout(() => this.setState({ isButtonDisabled: false }), 5000);

    return this.props.onLaunchClicked();

}

render () {
    return (
        <div className="client-playtest-state">
            <button className="btn bg-success" onClick={this.onLaunchClicked} 
         disabled={this.state.isButtonDisabled}>LAUNCH</button>
        </div>
    );
}
like image 198
Michael Peyper Avatar answered Sep 20 '22 11:09

Michael Peyper