How To Change Button Text On Click In React

Change button text on click in React

In this tutorial, we share with you methods to change button text on click in React. We will show you how to use the useState hook in conjunction with the onClick prop on the button element to do that. Let’s find out for further information.

Change button text on click in React

For changing button text on click in React, we use the useState hook and the onClick prop on the button element.

  • useState hook allows us to keep track of the value of the current text on the button element via a state variable.
  • Set the onClick property for the button element part. Every time the user presses the button, the text value of the button will be reset.

Let’s take a look at the following example to see how this method works:

import {useState} from 'react';
import './App.css'
 
const App = () => {
  const [text, setText] = useState('Next page');
 
  function handleClick() {
    if(text === 'Next page'){
      setText('Previous page');
    }else{
      setText('Next page');
    }
  }
 
  return (
        <div className='wrapper'>
            <b><h2 className='title'>LearnShareIT</h2></b>
            <button className='btn btn-primary' onClick={handleClick}>{buttonText}</button>
        </div>
  );
};
 
export default App;

Output:

In this example, the state variable ‘text‘ is used to track the text value of the button element. On the button, we use the onClick attribute to listen for the click event from the user. Every time the user presses the button, the function handleClick will be called, and the text value will be changed.

You can also change the text value after a timeout. This is usually applied when the program needs time to load an element.

Here is an example for you:

import {useState} from 'react';
import './App.css'
 
const App = () => {
  const [text, setText] = useState('Next page');
 
  function handleClick() {
      setText('Redirecting...');
 
   //wait 2 seconds before changing the text  
    setTimeout(() => {
      if(text === 'Next page'){
        setText('Previous page');
      }else{
        setText('Next page');
      }  
    }, 2000); 
  }
 
  return (
        <div className='wrapper'>
            <b><h2 className='title'>LearnShareIT</h2></b>
            <button className='btn btn-primary' onClick={handleClick}>{buttonText}</button>
        </div>
  );
};
 
export default App;

Output:

The setTimeout() method delays a specified amount of time before the button’s text value changes. Specifically, in the above example, we set it to two seconds.

Summary

To sum up, we have just shown you how to use the useState hook in conjunction with the onClick prop on the button element to change button text on click in React. Hopefully, this tutorial is helpful to you. Thanks for reading.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *