Home > OS >  What causes this weird response with the checkboxes react
What causes this weird response with the checkboxes react

Time:12-02

In the following example what causes the button to disable only after they have both been checked? Also is the button not displayed as disabled on render due to the way state works in react?

CodePudding user response:

Set calculated property direclty, to avoid redundant state

export default function App() {
  const [tosChecked, setTosChecked] = useState(false);
  const [privacyChecked, setPrivacyChecked] = useState(false);

  function handleTOSChecked(e) {
    setTosChecked((c) => !c);
    // checkCanSubmit();
  }

  function handlePrivacyChecked(e) {
    setPrivacyChecked((c) => !c);
    //  checkCanSubmit();
  }

 // set property directly
 const enableSubmit = tosChecked && privacyChecked;

 return (
   ...
   <button
          // here 
          disabled={!enableSubmit}
          type="submit"
          className="btn inline-flex justify-center rounded-md border border-transparent bg-indigo-600 py-2 px-4 text-sm font-medium text-white shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
        >

possible reason the code was not working as expected, could be due to batch updates or the disable prop needed to be inverted disabled={!canSubmit}

function handleTOSChecked(e) {
    setTosChecked(!tosChecked);
    // updates inside functions are batched and flushed out on next render cycle
    if (tosChecked && privacyChecked) {
      setCanSubmit(true);
    } else {
      setCanSubmit(false);
    }
    // the values of tosChecked and privacyChecked dont change
    // similar thing must be happing even if this code is inside a function called from this code
    console.log(tosChecked, privacyChecked);
}

Hope it helps

  • Related