Borislav Hadzhiev
Sun Apr 24 2022·2 min read
Photo by Filip Mroz
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;
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 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).