Reputation: 161
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>
);
}
Upvotes: 14
Views: 25814
Reputation: 51
let myInterval, disableOTPmilliseconds = 5000;
const sendOtp = async () => {
try {
if (userSessionData?.phone?.toString().trim()) {
const res = await axios.post(
`${process.env.REACT_APP_API_ENDPOINT}/api/users/send_otp`,
userSessionData
);
setDisableOtpButton(true);
myInterval = setInterval(() => {
return setDisableTimer((prev) => prev - 1);
}, 1000);
setTimeout(() => {
setDisableOtpButton(false);
setDisableTimer(disableOTPmilliseconds / 1000); // using disableOTPmilliseconds variable to define or change the milliseconds.
clearInterval(myInterval);
}, disableOTPmilliseconds);
}
};
Upvotes: 1
Reputation: 194
There are many ways to do it.
Here is my example:
React.js provides build in function called ComponentDidMount
Use build in setTimeout
method. Wit this method, you will be able to call React.js setState.
Here is not tested example of it:
componentDidMount(){
window.setTimeout(function () {
this.setState({
isButtonDisabled: false,
})
},5000)
}
If I understood your question correctly, this will work. After a user joins the site he will need to wait for 5 sec.
Please read React documentation.
Upvotes: 5
Reputation: 6944
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>
);
}
Upvotes: 24