JSFiddle - React, Tailwind, and code Playground
HTML
<!doctype html>
<h3>
Custom Checkbox
</h3>
<form>
<my-form-component required value="hello">I am a custom checkbox</my-form-component>
<p>
<button type="submit">Submit Form</button>
</p>
</form>
<h3>
Native Checkbox
</h3>
<form>
<input type="checkbox" required/> Native Checkbox
<p>
<button type="submit">Submit Form</button>
</p>
</form>
CSS
my-form-component:invalid {
background-color: red;
}
my-form-component:valid {
background-color: green;
}
JavaScript
class MyFormComponent extends HTMLElement {
static formAssociated = true;
set checked(value) {
this._checked = Boolean(value);
this._internals.ariaChecked = `${this._checked}`;
if (this._checked) {
this._internals.setValidity(
{},
);
} else {
this._internals.setValidity(
{ valueMissing: true },
'Should be ticked',
);
}
}
get checked() {
return this._checked;
}
constructor() {
super();
this._internals = this.attachInternals();
this.checked = false;
const shadowRoot = this.attachShadow({mode: 'open'});
const slot = document.createElement('slot');
shadowRoot.appendChild(slot);
this.setAttribute('tabindex', '0');
this.setAttribute('role', 'checkbox');
this.addEventListener('click', () => this.checked = !this.checked);
this.addEventListener('keydown', (e) => {
if (e.key === ' ') {
this.checked = !this.checked
}
});
}
}
window.customElements.define(
'my-form-component',
MyFormComponent
);