Last updated: Apr 7, 2024
Reading time·2 min
To change a button's text on click in React:
onClick
prop on the button element.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;
We set the onClick
prop on the button
element, so every time the button is
clicked, the handleClick()
function is invoked.
<button onClick={handleClick}>{buttonText}</button>
The useState hook is used to track the state.
const [buttonText, setButtonText] = useState('Click');
The string we passed to the useState
hook is used as the initial text of the
button element.
When the button is clicked, its handleClick function gets invoked where we set the new text.
function handleClick() { setButtonText('New text'); }
To change a button's text on click and change it back after a delay:
onClick
prop on the button element.setTimeout()
method to change the text back after a delay.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;
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.
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 that invokes a function after a delay.
function handleClick() { setButtonText('Loading...'); setTimeout(() => { setButtonText(initialText); }, 1000); // 👈️ Change text back after 1 second }
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've also written an article on how to create a delay (sleep) function in React.
If you need to clear a timeout or an interval in React, check out the following article.