![]() |
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 PrerequisitesSteps to Create React Application:Step 1: Create a react application by using this command npx create-react-app <<Project-Name>>
Step 2: After creating your project folder, use the following command to navigate to it cd <<Project-Name>>
Project Structure: The updated dependencies in package.json file will look like: "dependencies": { Approach 1: Using setTimeout() MethodIn 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
Output: Approach 2: Using Ternary OperatorStreamline a button’s text change using a ternary operator by modifying the “buttonText” state in the handleClick function. The operator evaluates the current value and switches between “Submit” and “Loading…”, prompting React to re-render the updated text on each click. Example: Below is the code example of the above explained approach Javascript
Output: ![]() Output |
Reffered: https://www.geeksforgeeks.org
ReactJS |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |