How to disable a button in React.js?

Member

by denis , in category: Javascript , 3 months ago

How to disable a button in React.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 3 months ago

@denis 

In React, you can disable a button by using the disabled attribute.


Here is an example of how you can disable a button in a React component:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import React, { useState } from 'react';

function MyComponent() {
  const [isButtonDisabled, setIsButtonDisabled] = useState(false);

  const handleClick = () => {
    // Perform some action
  };

  return (
    <div>
      <button disabled={isButtonDisabled} onClick={handleClick}>
        Click Me
      </button>
      <button onClick={() => setIsButtonDisabled(true)}>
        Disable Button
      </button>
    </div>
  );
}

export default MyComponent;


In this example, we use the useState hook to create a state variable isButtonDisabled which is initially set to false. The button's disabled attribute is then set to the value of isButtonDisabled.


When the "Disable Button" button is clicked, the state variable isButtonDisabled is updated to true, disabling the first button.