Home > Software design >  Make checkBox read only
Make checkBox read only

Time:09-27

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?

CodePudding user response:

if you want to make this checkbox disabled forever you just need to add disabled attribute like this:

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

but if you want to have control of this disabled attribute you should create a new boolean state by useState() and then just pass value to disabled attribute like that:

const [isDisabled, setIsDisabled] = useState(true);

return (
<input type="checkbox" disabled={isDisabled} onclick="return false"/>
)

CodePudding user response:

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

<input type="checkbox" disabled={this.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.

  • Related