Skip to main content
Since Shoelace 2.0 Code stable Pattern stable Figma ready

Checkbox

sl-checkbox

Checkboxes allow the user to toggle an option on or off.

Examples

Basic Checkbox

Financial products access
<sl-checkbox>Financial products access</sl-checkbox>
sl-checkbox Financial products access
= ts_form_for ... do |f|
  = f.input :access,
    as: :boolean,
    input_html: {
      label: "Financial products access"
    }
import SlCheckbox from '@teamshares/shoelace/dist/react/checkbox';

const App = () => <SlCheckbox>Checkbox</SlCheckbox>;

Description

Add descriptive help text to individual checkbox items with the description attribute. For descriptions that contain HTML, use the description slot instead.

Financial products access
<sl-checkbox description="Grants access to cash account and charge card features">Financial products access</sl-checkbox>
sl-checkbox[
  description="Grants access to cash account and charge card features"
]
  | Financial products access
= ts_form_for ... do |f|
  = f.input :access,
    as: :boolean,
    input_html: {
      label: "Financial products access",
      description: "Grants access to cash account and charge card features"
    }
import SlCheckbox from '@shoelace-style/shoelace/dist/react/checkbox';

const App = () => <SlCheckbox help-text="What should the user know about the switch?">Label</SlCheckbox>;

Contained

Add the contained attribute to draw a card-like container around a checkbox. Add to a Checkbox Group to draw a container around each checkbox in the group. This style is useful for giving more emphasis to a checkbox or list of checkboxes.

Financial products access

Initiate outbound transfers Approve outbound transfers Export transactions
<sl-checkbox description="Grants access to cash account and charge card features" contained>Financial products access</sl-checkbox>
<br/>
<br/>
<sl-checkbox-group label="Financial products permissions" contained>
  <sl-checkbox description="Requires separate initiators and approvers">Initiate outbound transfers</sl-checkbox>
  <sl-checkbox description="Requires separate initiators and approvers">Approve outbound transfers </sl-checkbox>
  <sl-checkbox description="Applies to both cash account and charge card" disabled>Export transactions</sl-checkbox>
</sl-checkbox-group>
sl-checkbox[
  description="Grants access to cash account and charge card features"
  contained=true
]
  | Financial products access
br
br
sl-checkbox-group[
  label="Financial products permissions"
  contained=true
]
  sl-checkbox description="Requires separate initiators and approvers"
  | Initiate outbound transfers
  sl-checkbox description="Requires separate initiators and approvers"
  | Approve outbound transfers
  sl-checkbox description="Applies to both cash account and charge card" disabled
  | Export transactions
/*
  When rendering `sl-checkbox-group` with ts_form_for, pass additional
  attributes such as `disabled` and `description` as extra items
  in the collection array after the label and value.
  By default Simple Form will use the first item
  as the label and the second item as the value, then pass
  any additional array items as attributes on the `sl-checkbox`.
*/

= ts_form_for ... do |f|
  = f.input :access,
    as: :boolean,
    input_html: {
      label: "Financial products access",
      description: "Grants access to cash account and charge card features",
    }
  br
  br
  = f.input :access_options,
    as: :check_boxes,
    label: "Financial products permissions",
    collection: [
      [
        "Initiate outbound transfers",
        "initiate_outboard",
        description: "Requires separate initiators and approvers",
      ],
      [
        "Approve outbound transfers",
        "approve_outbound",
        description: "Requires separate initiators and approvers",
      ],
      [
        "Export transactions",
        "export",
        description: "Applies to both cash account and charge card",
        disabled: true,
      ],
    ],
    wrapper_html: {
      contained: true,
    }
import { SlCheckbox } from '@teamshares/shoelace/dist/react';
const App = () => (
  <>
    <SlCheckbox contained style="width: 100%;">
      Checked
    </SlCheckbox>
    <SlCheckbox contained disabled style="width: 100%;">
      Disabled
    </SlCheckbox>
    <SlCheckbox contained checked style="width: 100%;">
      Checked
      <div slot="help-text">A short description about this option</div>
    </SlCheckbox>
  </>
);

Selected Content

Use the selected-content slot to display additional content (such as an input field) inside a contained checkbox when it is checked. The slot is unstyled by default. Use ::part(selected-content) to style the content as needed.

Grant financial products access

A mobile number is required to grant this user access to financial products. The number will be used for login verification.

<sl-checkbox style="width:100%" contained>Grant financial products access
  <div slot="selected-content">
    <p>A mobile number is required to grant this user access to financial products. The number will be used for login verification.</p>
    <sl-input style="width: 280px;" label="Mobile number" type="tel" required optional-icon></div>
</sl-checkbox>
<style>
  sl-checkbox::part(selected-content) {
    font-size: 14px;
    font-weight: normal;
    color: #6D7176;
  }
</style>
sl-checkbox[
  style="width:100%"
  contained=true
]
  | Grant financial products access
  div slot="selected-content"
    p A mobile number is required to grant this user access to financial products. The number will be used for login verification.
    sl-input[
      style="width: 280px;"
      label="Mobile number"
      type="tel"
      required=true
      optional-icon=true
    ]
css:
    sl-checkbox::part(selected-content) {
    font-size: 14px;
    font-weight: normal;
    color: #6D7176;
  }
/*
  NOTE: `ts_form_for` doesn't support slots. The `selected-content` slot
  cannot be used for checkboxes rendered with `ts_form_for`.
*/
import { SlCheckbox } from '@teamshares/shoelace/dist/react';
const App = () => (
  <>
    <SlCheckbox contained style="width: 100%;">
      Checked
    </SlCheckbox>
    <SlCheckbox contained disabled style="width: 100%;">
      Disabled
    </SlCheckbox>
    <SlCheckbox contained checked style="width: 100%;">
      Checked
      <div slot="help-text">A short description about this option</div>
    </SlCheckbox>
  </>
);

Checked

Use the checked attribute to activate the checkbox.

Financial products access
<sl-checkbox checked>Financial products access</sl-checkbox>
sl-checkbox checked=true Financial products access
= ts_form_for ... do |f|
  = f.input :access,
    as: :boolean,
    input_html: {
      label: "Financial products access",
      checked: true,
    }
import SlCheckbox from '@teamshares/shoelace/dist/react/checkbox';

const App = () => <SlCheckbox checked>Checked</SlCheckbox>;

Indeterminate

Use the indeterminate attribute to make the checkbox indeterminate.

Indeterminate
<sl-checkbox indeterminate>Indeterminate</sl-checkbox>
sl-checkbox indeterminate=true Indeterminate
= ts_form_for ... do |f|
  = f.input :access,
    as: :boolean,
    input_html: {
      label: "Financial products access",
      indeterminate: true,
    }
import SlCheckbox from '@teamshares/shoelace/dist/react/checkbox';

const App = () => <SlCheckbox indeterminate>Indeterminate</SlCheckbox>;

Disabled

Use the disabled attribute to disable the checkbox.

Disabled
<sl-checkbox disabled>Disabled</sl-checkbox>
sl-checkbox disabled=true Disabled
= ts_form_for ... do |f|
  = f.input :access,
    as: :boolean,
    input_html: {
      label: "Financial products access",
      disabled: true,
    }
import SlCheckbox from '@teamshares/shoelace/dist/react/checkbox';

const App = () => <SlCheckbox disabled>Disabled</SlCheckbox>;

Custom Validity

Use the setCustomValidity() method to set a custom validation message. This will prevent the form from submitting and make the browser display the error message you provide. To clear the error, call this function with an empty string.

Check me
Submit
<form class="custom-validity">
  <sl-checkbox>Check me</sl-checkbox>
  <br />
  <sl-button type="submit" variant="primary" style="margin-top: 1rem;">Submit</sl-button>
</form>
<script type="module">
  const form = document.querySelector('.custom-validity');
  const checkbox = form.querySelector('sl-checkbox');
  const errorMessage = `Do not forget to check me!`;

  // Set initial validity as soon as the element is defined
  customElements.whenDefined('sl-checkbox').then(async () => {
    await checkbox.updateComplete;
    checkbox.setCustomValidity(errorMessage);
  });

  // Update validity on change
  checkbox.addEventListener('sl-change', () => {
    checkbox.setCustomValidity(checkbox.checked ? '' : errorMessage);
  });

  // Wait for controls to be defined before attaching form listeners
  await Promise.all([
    customElements.whenDefined('sl-checkbox'),
  ]).then(() => {
    form.addEventListener('submit', event => {
      event.preventDefault();
      alert('All fields are valid!');
    });
  });
</script>
form.custom-validity
  sl-checkbox Check me
  br
  sl-button type="submit" variant="primary" style="margin-top: 1rem;" Submit

javascript:
  const form = document.querySelector(.custom-validity);
  const checkbox = form.querySelector(sl-checkbox);
  const errorMessage = `Do not forget to check me!`;

  // Set initial validity as soon as the element is defined
  customElements.whenDefined(sl-checkbox).then(() => {
    checkbox.setCustomValidity(errorMessage);
  });

  // Update validity on change
  checkbox.addEventListener(sl-change, () => {
    checkbox.setCustomValidity(checkbox.checked ?  : errorMessage);
  });

  // Wait for controls to be defined before attaching form listeners
  await Promise.all([
    customElements.whenDefined('sl-checkbox'),
  ]).then(() => {
    // Handle form submit
    form.addEventListener(submit, event => {
      event.preventDefault();
      alert(All fields are valid!);
    });
  });

Usage

Testing

With Cypress

Adding data-test-id to a component

To test sl-checkbox, add the data-test-id attribute directly to the component:

  sl-checkbox[
    data-test-id="checkbox-test"
  ] 
    | Checkbox test

To test sl-checkbox implemented with ts_form_for, add data-test-id to input_html:

    = ts_form_for ... do |f|
      = f.input :input_name,
        as: :boolean,
        input_html: { 
          label: "Checkbox text",
          data: { 
            test_id: "checkbox-test"
          }
        }

Cypress commands for sl-checkbox

To check the checkbox:

  cy.slCheckboxCheck(`[data-test-id="checkbox-test"]`);

To uncheck the checkbox:

  cy.slCheckboxUncheck(`[data-test-id="checkbox-test"]`);

To verify the checkbox is checked:

  cy.get(`[data-test-id="checkbox-test"]`).should("have.prop", "checked", true);

To verify the checkbox is NOT checked:

  cy.get(`[data-test-id="checkbox-test"]`).should("have.prop", "checked", false);

Component Props

Property Default Details
name ''

string

The name of the checkbox, submitted as a name/value pair with form data.

value

string

The current value of the checkbox, submitted as a name/value pair with form data.

size 'medium'

'small' | 'medium' | 'large'

The checkbox’s size.

disabled false

boolean

Disables the checkbox.

checked false

boolean

Draws the checkbox in a checked state.

indeterminate false

boolean

Draws the checkbox in an indeterminate state. This is usually applied to checkboxes that represents a “select all/none” behavior when associated checkboxes have a mix of checked and unchecked states.

contained false

boolean

Draws a container around the checkbox.

horizontal false

boolean

Applies styles relevant to checkboxes in a horizontal layout.

defaultChecked false

boolean

The default value of the form control. Primarily used for resetting the form control.

form ''

string

By default, form controls are associated with the nearest containing <form> element. This attribute allows you to place the form control outside of a form and associate it with the form that has this id. The form must be in the same document or shadow root for this to work.

required false

boolean

Makes the checkbox a required field.

description ''

string

The checkbox’s help text. If you need to display HTML, use the description slot instead.

validity

Gets the validity state object

validationMessage

Gets the validation message

updateComplete A read-only promise that resolves when the component has finished updating.

Learn more about attributes and properties.

Slots

Name Details
(default) The checkbox’s label.
description A description of the checkbox’s label. Serves as help text for a checkbox item. Alternatively, you can use the description attribute.
selected-content Use to nest rich content (like an input) inside a selected checkbox item. Use only with the contained style.

Learn more about using slots.

Events

Name Name Name React Event Details
sl-blur sl-blur sl-blur onSlBlur

Emitted when the checkbox loses focus.

sl-change sl-change sl-change onSlChange

Emitted when the checked state changes.

sl-focus sl-focus sl-focus onSlFocus

Emitted when the checkbox gains focus.

sl-input sl-input sl-input onSlInput

Emitted when the checkbox receives input.

sl-invalid sl-invalid sl-invalid onSlInvalid

Emitted when the form control has been checked for validity and its constraints aren’t satisfied.

Learn more about events.

Methods

Name Details
click()

Simulates a click on the checkbox.

focus()

options: FocusOptions

Sets focus on the checkbox.

blur()

Removes focus from the checkbox.

checkValidity()

Checks for validity but does not show a validation message. Returns true when valid and false when invalid.

getForm()

Gets the associated form, if one exists.

reportValidity()

Checks for validity and shows the browser’s validation message if the control is invalid.

setCustomValidity()

message: string

Sets a custom validation message. The value provided will be shown to the user when the form is submitted. To clear the custom validation message, call this method with an empty string.

Learn more about methods.

CSS Parts

Name Description
base The component’s base wrapper.
control The square container that wraps the checkbox’s checked state.
control--checked Matches the control part when the checkbox is checked.
control--indeterminate Matches the control part when the checkbox is indeterminate.
checked-icon The checked icon, an <sl-icon> element.
indeterminate-icon The indeterminate icon, an <sl-icon> element.
label The container that wraps the checkbox’s label.
description The container that wraps the checkbox’s description.
selected-content The container that wraps optional content that appears when a checkbox is checked.

Learn more about customizing CSS parts.

Dependencies

This component automatically imports the following dependencies.

  • <sl-icon>