javascripthtmlreactjscheckbox

Make checkBox read only


I want to have a read-Only checkbox and disable the toggle( checked /unchecked) when I click the checkbox. Which possiblities I have? This is my code:

<label className="checkbox">
  <input type="checkbox"/>
</label>

I read a post where this workaround is proposed:

<input type="checkbox" onclick="return false" />

...but how can I use it in React?


Solution

  • Assuming you have this variable to control if the checkbox is enabled/disabled

    const [isCheckboxDisabled, setCheckboxDisabled] = useState(false);
    

    You can disable the checkbox by means of the disabled attribute like:

    <input type="checkbox" disabled={isCheckboxDisabled} />
    

    Or with the workaround you found

    <input type="checkbox" onclick="onCheckboxClick" />
    
    function onCheckboxClick(e) {
       if (this.isCheckboxDisabled) {
          e.preventDefault();
          return false;
       }
    }
    

    I would suggest the first strategy, as is ARIA compliant, and changes the input styles so it is visibly disabled.