How to usesetTimeout() Method in ReactJS
In this method, the button text swiftly changes to āLoadingā¦ā on click using `setTimeout()` and `setButtonText()`. After a deliberate 2-second delay, the original text is restored, creating a brief loading state for enhanced user experience.
Example: Below is the code example of the above explained approach
Javascript
import React, { useState } from 'react' ; function App() { const [buttonText, setButtonText] = useState( 'Submit' ); const handleClick = () => { setButtonText( 'Loading...' ); setTimeout(() => { setButtonText( 'Submit' ); }, 2000); // Reverts back to 'Submit' after 2 seconds }; return ( <div style={styles.container}> <h1 style={styles.heading}> w3wiki </h1> <button onClick={handleClick} style={styles.btn}> {buttonText} </button> </div> ); } export default App; const styles = { container: { textAlign: 'center' , margin: 'auto' , padding: '20px' , width: 400, }, heading: { fontSize: '34px' , marginBottom: '10px' , color: "green" , borderBottom: "3px solid crimson" , paddingBottom: 20, borderRadius: "8px" , }, btn: { backgroundColor: 'green' , fontSize: 20, color: 'white' , cursor: 'pointer' , margin: 10, padding: 15, borderRadius: "8px" , border: "none" , boxShadow: "0px 0px 10px 0px grey" , }, }; |
Output:
How to Change Button Text on Click in ReactJS ?
In this article, we will learn about diverse methods for altering button text dynamically upon clicking on the button. React, a widely embraced JavaScript library for crafting user interfaces provides several approaches to seamlessly achieve this functionality. The key lies in manipulating the componentās state and adjusting its rendering logic to reflect the updated button text based on user interactions.
We will discuss the following two approaches to change button text on click in React:
Table of Content
- Using setTimeout() Method
- Using Ternary Operator
Contact Us