React: How to Disable a Button after One Click

Updated: March 3, 2023 By: Snowball Post a comment

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:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles