onClick functionality not working even when i enabling the button on certain condition
function App() {
const buttonRef = useRef(null);
const name = 'Pilla'
if(name === 'Pilla'){
buttonRef.current.setAttribute('disabled', false)
}else{
buttonRef.current.setAttribute('disabled', true)
}
const handleButtonClick = () => {
console.log('Button clicked!');
};
return (
<button ref={buttonRef} onClick={handleButtonClick}>
Click Me
</button>
)}
2
Answers
You are using wrong way to disable button in react. Here is right way to use.
As Andy mentioned in their comment you don’t need a
ref
to disable the element. You can set thedisabled
attribute directly on the button like demonstrated below.