Home > Software design >  Toggle between enable/disable button doesnt work
Toggle between enable/disable button doesnt work

Time:09-23

I'm learning reactjs and this is my very first code. Onclick the input fields will be disabled, however, when I click on enable the fields are still disabled. How can I fix this?

import React,{useState} from 'react';
import '../css/formContact.css';


export function Contact(){

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

    function handleDisabling(){
        setDisabled({isDisabled : true})
    }

    function handleEnabling(){
        setDisabled({isDisabled : false})
    }

    return(
        <div id = 'contact'>
            <h2>Contact</h2>
            <div className = 'form-contact'>
                <span>Name: <input type = 'text' disabled={isDisabled}/></span>
                <span>Surname: <input type = 'text'disabled={isDisabled}/></span>
                <span>Address: <input type = 'text'disabled={isDisabled}/></span>
                <span>G.P.A.: <input type = 'text'disabled={isDisabled}/></span>
                { isDisabled 
                    ? <button className = 'btn-add-date' onClick={() => handleEnabling()}>Enable</button>
                    : <button className = 'btn-add-date' onClick={() => handleDisabling()}>Disable</button>
                }
            </div>
        </div>
    )
}

Problem solved:

  function handleEnabling(){
        setDisabled(false)
    }

CodePudding user response:

setDisabled(true) instead of setDisable({ isDisabled : true }) will work

CodePudding user response:

You are passing wrong arguments to the state updating function (in your case setDisabled(...)). Unlike in class components, You don't have to pass the new value as an object. Just pass the value as it is. in your case you have to use

function handleDisabling() {
  setDisabled(true);
}

function handleEnabling() {
  setDisabled(false);
}

here is a working version of your code Codesandbox

  • Related