Skip to main content

Checkbox

import { Checkbox } from '@dr.pogodin/react-utils';

The Checkbox component implements checkboxes themed with React Themes.

Demo (expand to see the source code)

Managed two-states checkbox
Managed three-states checkbox
Managed three-states checkbox
import { useState } from 'react';

import { Checkbox } from '@dr.pogodin/react-utils';

export default function CheckboxExample() {
const [checkbox2, setCheckbox2] = useState<boolean>(true);
const [checkbox3a, setCheckbox3a] = useState<boolean | 'indeterminate'>('indeterminate');
const [checkbox3b, setCheckbox3b] = useState<boolean | 'indeterminate'>('indeterminate');
return (
<>
<Checkbox
checked={checkbox2}
label="Managed two-states checkbox"
onChange={(e) => setCheckbox2(e.target.checked)}
/>
<Checkbox
checked={checkbox3a}
label="Managed three-states checkbox"
onChange={() => {
switch (checkbox3a) {
case true: return setCheckbox3a(false);
case 'indeterminate': return setCheckbox3a(true);
default: return setCheckbox3a('indeterminate');
}
}}
/>
<Checkbox
checked={checkbox3b}
disabled
label="Managed three-states checkbox"
onChange={() => {
switch (checkbox3b) {
case true: return setCheckbox3b(false);
case 'indeterminate': return setCheckbox3b(true);
default: return setCheckbox3b('indeterminate');
}
}}
/>
</>
);
}

Properties

  • checkedboolean | "indeterminate" | undefined — Checkbox value.

    info

    To implement indeterminate state we don't use indeterminate property of the underlying <input> element, we rather simply append indeterminate theme class to the underlying <input> and style it accordingly.

    There won't be a way to detect the current «indeterminate» state of the checkbox from the event argument of onChange hook, it will be necessary to fully manage it via the external state.

  • disabledboolean | undefined — Disables the checkbox.

  • labelReact.ReactNode — Checkbox label.

  • onChangefunction — State change handler.

  • testIdstring | undefined — Sets data-testid attribute to the underlying <input> element; it is intended to faciliate testing with @testing-library/dom. Ignored in production builds.

  • themeCheckboxThemeAd hoc React Themes theme.

  • Accepts other props of themed components.

CheckboxTheme

Valid theme keys are:

  • checkbox — Applied to the underlying checkbox <input> element.

  • container — Applied to the root checkbox element.

  • disabled — Applied to the root checkbox container if the component is disabled.

  • indeterminate — Applied to the underlying <input> element when the component is in the «indeterminate» state.

  • label — Applied to the checkbox label element.

See React Themes documentation for details on visual component theming.