Change button text on click in React

avatar

Borislav Hadzhiev

Last updated: Apr 24, 2022

banner

Photo from Unsplash

Change button text on click in React #

To change a button's text on click in React:

  1. Track the text of the button in a state variable.
  2. Set the onClick prop on the button element.
  3. When the button gets clicked, update the state variable.
App.js
import {useState} from 'react'; const App = () => { const [buttonText, setButtonText] = useState('Click'); function handleClick() { setButtonText('New text'); } return ( <div> <button onClick={handleClick}>{buttonText}</button> </div> ); }; export default App;

change button text on click

To change a button's text on click and change it back after a delay:

  1. Track the text of the button in a state variable.
  2. Set the onClick prop on the button element.
  3. When the button gets clicked, update the state variable.
  4. Use the setTimeout() method to change the text back after a delay.
App.js
import {useState} from 'react'; const App = () => { const initialText = 'Click'; const [buttonText, setButtonText] = useState(initialText); function handleClick() { setButtonText('Loading...'); setTimeout(() => { setButtonText(initialText); }, 1000); // 👈️ change text back after 1 second } return ( <div> <button onClick={handleClick}>{buttonText}</button> </div> ); }; export default App;

set button text on click and revert

The text of the button is tracked using the useState hook.

When we call the setButtonText function with the new text, the button element gets re-rendered and shows the updated text.

We set the onClick prop on the button element, so every time the button is clicked, the handleClick function gets invoked.

In our handleClick function, we update the text of the button and use the setTimeout method to set up a timer which invokes a function after a delay.

The second parameter the setTimeout method takes is the delay after which we want to call the function (in milliseconds).

The function from the example is invoked after 1000 ms (one second).

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.