This example below shows you how to disable a certain button after it is clicked once in React. This can be useful in cases where you want to prevent the user from repeatedly clicking it multiple times, such as submitting a form, purchasing a product at a promotional price (one can only be purchased per person), etc.
Example Preview
The complete code (with explanations):
// KindaCode.com
// src/App.js
import { useState } from 'react';
function App() {
// this determines whether the button is disabled or not
const [isDisabled, setIsDisabled] = useState(false);
// This function is called when the button is clicked the first time
const handleClick = () => {
alert('Hi there!');
setIsDisabled(true);
};
return (
<div style={styles.container}>
<button
disabled={isDisabled}
onClick={handleClick}
// this is the style for the button
style={isDisabled ? styles.buttonDisabled : styles.button}
>
Button
</button>
</div>
);
}
// Styles
const styles = {
container: {
width: '100vw',
height: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
button: {
padding: '10px 30px',
cursor: 'pointer',
},
buttonDisabled: {
padding: '10px 30px',
cursor: 'not-allowed',
},
};
export default App;
Further reading:
- React: Programmatically Add/Remove CSS Classes
- React: Show a Loading Dialog (without any libraries)
- How to Create a Read More/Less Button in React
- React: 5+ Ways to Store Data Locally in Web Browsers
- React + TypeScript: setInterval() example (with hooks)
- React Native FlatList: Tutorial and Examples
You can also check our React category page and React Native category page for the latest tutorials and examples.