Home > database >  Trying to disable a button onPress - ReactJS
Trying to disable a button onPress - ReactJS

Time:06-15

I'm kinda new to ReactJs, I'm trying to disable a button in my app when that button is pressed. I have a function called "disableButtonEG" but it does nothing when I pressed it.

 function disableButtonEG= () => {
        button.disabled = true
   };

<Button
                title="Press to disable"
                buttonStyle={{backgroundColor: PrimaryColor, borderRadius: 10}}
                titleStyle={{fontSize:13}}        
                onPress={disableButtonEG}                     
/>

Any assist is appreciated

CodePudding user response:

Try this,

function App() {
  const [disable, setDisable] = React.useState(false);

  return (
    <button disabled={disable} onClick={() => setDisable(true)}>
      Click me!
    </button>
  );
}

CodePudding user response:

I don't think onPress handler exists in button. Please try with onMouseDown instead of onPress

CodePudding user response:

Looks like you wrote the function syntax wrong. If you are still having problems after fixing it, You can use state. For example, I have a disabled state which has an initial value of false

const [disabled, setDisabled] = useState(false);

And a function that will change it to true

const disableButtonEG = () => {
    setDisabled(true);
};
  

Then modify the Button component like this

<Button
            title="Press to disable"
            buttonStyle={{ backgroundColor: PrimaryColor, borderRadius: 10 }}
            titleStyle={{ fontSize: 13 }}
            disabled={disabled}
            onPress={disableButtonEG}
        />

CodePudding user response:

Buttons have a disabled attribute, you can set this to true or false to disable the button. You should also be using onClick instead of onPress.

Here is an example of one way to achieve what you are trying to do in ReactJS

import React from "react";
function App() {
  const [disable, setDisable] = React.useState(false);

  return (
    <button disabled={disable} onClick={() => setDisable(true)}>
      Disable Button
    </button>
  );
}
export default App

EDIT: Disable via function

import React from "react";
function App() {
  const [disable, setDisable] = React.useState(false);
  function disableButton() {
     setDisable(true)
  }
  return (
    <button disabled={disable} onClick={disableButton}>
      Disable Button
    </button>
  );
}
export default App
  • Related