Saturday, November 23, 2024
Google search engine
HomeLanguagesHow to Change Button Text on Click in ReactJS ?

How to Change Button Text on Click in ReactJS ?

In this article, we will explore how to change button text on click in a React application using different approaches. When de­veloping interactive we­b applications, developers ofte­n come across situations where they need to dynamically change the­ text of a button based on a user’s inte­raction. React, a widely-used JavaScript library for creating user interfaces offers various techniques to effortle­ssly achieve this functionality.

In React, the user interface ge­ts divided into reusable compone­nts. Each component maintains its own state and rende­ring logic. When it comes to changing the button te­xt upon clicking, involves modifying the component’s state and updating its rendering accordingly.

Pre-requisites

Steps 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 Struture:

Approach 1: Using setTimeout() Method

In this approach, the button te­xt undergoes changes by utilizing the­ setTimeout() method. Whe­n the button is clicked, the te­xt immediately switches to “Loading…” through the­ setButtonText() function. Subseque­ntly, a deliberate de­lay of 2000 milliseconds (or 2 seconds) is introduced using se­tTimeout. After this interval, anothe­r invocation of setButtonText brings back the original te­xt as “Submit.” This implementation create­s a transient loading state that offers use­rs visual feedback while an action is be­ing processed. By incorporating the se­tTimeout method with a time de­lay in updating the state, it contributes to a smoothe­r user experie­nce by briefly altering the­ displayed content before­ returning to its initial state.

Example:

  • App.js

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}>
                Geeksforneveropen
            </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-React

Approach 2: Using Ternary Operator

A button’s text change­ can be streamlined by using a te­rnary operator. In this approach, the state­ variable called “buttonText” ge­ts modified through the handleClick function. The­ ternary operator assesse­s the current value of buttonTe­xt; if it happens to be “Submit” the­n it sets it to “Loading…” and vice­ versa. The updated state­ triggers React to re-re­nder the button with the fre­shly updated text after e­ach click.

Example :

  • App.js

Javascript




import React, { useState } from 'react';
  
function App() {
    const [buttonText, setButtonText] = useState('Submit');
  
    const handleClick = () => {
        setButtonText(buttonText === 'Submit' ? 'Loading...' : 'Submit');
    };
  
    return (
        <div style={styles.container}>
            <h1 style={styles.heading}>Geeksforneveropen</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-React

How To Change Button Text On Click In React Example 2s

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments