Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Materials-UI disable a button in a handler

Trying to disable a button after the user clicks on it, but from a handler function.

I have referenced these two similar questions: React Material UI: How to give a button a custom color when disabled? Change disable attribute in react select with material UI

I thought changing the color would be a good practice step, but that didn't work. When I use color='primary' the button is blue, and that's what I want for the initial state. However, when the page loads, the button is now gray (looks disabled, but the mouse can still click on it).

My original blue button:

 <Button id='UploadButton' onClick={uploadButtonClicked} 
         variant="contained" color="primary">Upload</Button>

My revised button (trying to use state for color):

 <Button id='UploadButton' onClick={uploadButtonClicked} 
         disabled="{uploadButtonDisabled}" 
         variant="contained" 
         color="{uploadButtonColor}">Upload</Button>

My state & handler:

       const [uploadButtonColor, setUploadButtonColor] =
React.useState('primary');   
       const [uploadButtonDisabled,
setUploadButtonDisabled] = React.useState('false');
      
       const uploadButtonClicked = () => {
          // will post data to a REST API here, then disable the button 
          setUploadButtonColor('red')
          setUploadButtonDisabled('true')
      }

Do I need to use color schema to make it look disabled, or can I just add the disabled word, or set disabled to true?

This is how the doc shows a disabled button:

<Button variant="outlined" disabled>
    Upload 
</Button>
like image 335
NealWalters Avatar asked Aug 26 '26 19:08

NealWalters


1 Answers

Do not put quotes around the property/substitution values disabled={isDisabled} not disabled='{isDisabled}' (and same with color).

You can use this :

import Button from "@material-ui/core/Button";

function SampleButtons(props) {
  let [isDisabled, setIsDisabled] = React.useState(false)
  return (
    <React.Fragment>
      <Button variant="contained" onClick={() => setIsDisabled(true)} disabled={isDisabled}>Button</Button>
    </React.Fragment>
  );
}
like image 109
Martin J Avatar answered Aug 29 '26 09:08

Martin J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!