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>
);
}
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.
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.
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.
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>
);
}
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