skip to Main Content

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


  1. You are using wrong way to disable button in react. Here is right way to use.

    
    function App() {
      const name = 'Pilla';
    
      const handleButtonClick = () => {
        console.log('Button clicked!');
      };
    
      return (
        <button onClick={handleButtonClick} disabled={name === 'Pilla'}>
          Click Me
        </button>
      )
    }
    
    export default App;
    
    Login or Signup to reply.
  2. As Andy mentioned in their comment you don’t need a ref to disable the element. You can set the disabled attribute directly on the button like demonstrated below.

    function App() {
      const name = 'Pilla'
      
      const handleButtonClick = () => {
        console.log('Button clicked!');
      };
    
      return (
       <button disabled={name !== 'Pilla'} onClick={handleButtonClick}>
            Click Me
       </button>
      )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search