Checkboxes are form elements used to select one or multiple items from a list.
Basic Usage
Related checkboxes should be grouped within the Form Group control.
The label/checkbox association will be handled via the passed in id
if one is supplied or via an auto-generated id
if not supplied.
Checkboxes can either be controlled or uncontrolled. If you pass in a checked
prop, it is a controlled input. That means that to change the checkbox's state, you must updated the checked
prop's value.
If you do not want to have your checkbox be in a controlled state, but need the initial checked value to be set, pass in the defaultChecked
prop with the value you would like on initial render.
See also: Radio Buttons and Toggle Switches.
import React from 'react';import { Checkbox, FormGroup } from 'react-magma-dom';export function Example() {const [checked, updateChecked] = React.useState<boolean>(false);function handleUpdateChecked() {updateChecked(!checked);}return (<FormGroup labelText="Choose one or more"><CheckboxdefaultCheckedid="customId"labelText="Uncontrolled checkbox"/><Checkboxchecked={checked}labelText="Controlled checkbox"onChange={handleUpdateChecked}/><Checkbox labelText="Checkbox label is really long and can wrap to multiple lines lorem ipsum dolar sit amet is really long and can wrap to multiple lines" /></FormGroup>);}
Colors
By default, the checkboxes use the theme's primary color. But any other color may be passed in.
import React from 'react';import { Checkbox, FormGroup, magma } from 'react-magma-dom';export function Example() {return (<FormGroup labelText="Choose one or more colors"><Checkbox checked labelText="Default color" /><Checkboxcheckedcolor={magma.colors.success}labelText="Success color"/><Checkbox checked color={magma.colors.danger} labelText="Danger color" /><Checkboxcheckedcolor={magma.colors.warning}labelText="Warning color"/><Checkbox checked color={magma.colors.info} labelText="Info color" /></FormGroup>);}
Disabled
Adding the optional boolean prop disabled
will apply disabled styles and add the disabled attribute to the underlying HTML element.
import React from 'react';import {Checkbox,FormGroup,IndeterminateCheckbox,magma,} from 'react-magma-dom';export function Example() {return (<FormGroup labelText="Choose one or more"><Checkboxcolor={magma.colors.success}disabledlabelText="Disabled checkbox"/><Checkboxcheckedcolor={magma.colors.success}disabledlabelText="Disabled checked checkbox"/><IndeterminateCheckboxcolor={magma.colors.success}disabledlabelText="Disabled indeterminate checkbox"status="indeterminate"/></FormGroup>);}
Inverse
isInverse
is an optional boolean prop, that may be passed in when the component is to be displayed on a dark background.
import React from 'react';import {Card,CardBody,Checkbox,FormGroup,IndeterminateCheckbox,IndeterminateCheckboxStatus,} from 'react-magma-dom';export function Example() {return (<Card isInverse><CardBody><FormGroup isInverse labelText="Choose inverse options"><Checkbox isInverse labelText="Inverse" /><Checkbox checked isInverse labelText="Inverse checked" /><IndeterminateCheckboxstatus={IndeterminateCheckboxStatus.indeterminate}isInverselabelText="Indeterminate inverse"/><Checkbox disabled isInverse labelText="Disabled inverse" /><CheckboxcheckeddisabledisInverselabelText="Disabled checked inverse"/><IndeterminateCheckboxdisabledisInverselabelText="Disabled indeterminate inverse"status={IndeterminateCheckboxStatus.indeterminate}/><CheckboxerrorMessage="Please check this box"isInverselabelText="Checkbox with error"/></FormGroup></CardBody></Card>);}
Text Position
Use the optional prop textPosition
to position the label text on either side of the checkbox.
The textPosition
property takes the values left
and right
. The default value is right
.
import React from 'react';import { Checkbox, CheckboxTextPosition, FormGroup } from 'react-magma-dom';export function Example() {return (<FormGroup labelText="Text positions"><CheckboxlabelText="Text left"textPosition={CheckboxTextPosition.left}/><Checkbox labelText="Text right" /></FormGroup>);}
Error at Group Level
The errorMessage
prop can be used on the FormGroup
component to display an error message for the group. Each checkbox within the group will display with error styles.
import React from 'react';import { Checkbox, FormGroup } from 'react-magma-dom';interface CheckboxState {yellow: boolean;red: boolean;green: boolean;}export function Example() {const [hasError, setHasError] = React.useState<boolean>(true);const [state, setState] = React.useState<CheckboxState>({yellow: false,red: false,green: false,});const handleChange = (event: React.Change) => {setState({ ...state, [event.target.value]: event.target.checked });};React.useEffect(() => {setHasError(!state.yellow && !state.red && !state.green);}, [state]);return (<><p>* indicates required fields</p><FormGrouplabelText="Choose one or more colors *"errorMessage={hasError ? 'Please choose at least one color' : null}><Checkboxchecked={state.yellow}labelText="Yellow 1"name="color"onChange={handleChange}value="yellow"/><Checkboxchecked={state.red}labelText="Red"name="color"onChange={handleChange}value="red"/><Checkboxchecked={state.green}labelText="Green"name="color"onChange={handleChange}value="green"/></FormGroup></>);}
Error at Checkbox Level
An errorMessage
can also be supplied to an individual checkbox, without the use of a FormGroup
.
The required
attribute can be used on a single checkbox if that individual checkbox is required.
An example of when to use this would be for a terms and conditions checkbox.
import React from 'react';import { Checkbox } from 'react-magma-dom';export function Example() {const [hasError, setHasError] = React.useState<boolean>(true);function handleChange(event: React.ChangeEventHandler) {setHasError(!event.target.checked);}return (<CheckboxerrorMessage={hasError ? 'You must agree to the terms and conditions' : null}labelText="I agree to the terms and conditions"onChange={handleChange}required/>);}
Visually Hidden Label
Adding the isTextVisuallyHidden
prop will make the label text available to screen readers, but will hide it visually.
isTextVisuallyHidden
prop; it should only be used in rare circumstances when the purpose of the checkbox is conveyed in another way. While screen readers will announce the label when the checkbox gains focus, it is still best to have a visual label. This is especially helpful for individuals with cognitive disabilities and users who have fine motor control limitations.import React from 'react';import { Checkbox } from 'react-magma-dom';export function Example() {return <Checkbox labelText="Hidden checkbox" isTextVisuallyHidden />;}
Custom Styles
Custom styles can be passed into the Checkbox component. The containerStyle
property will apply to the container.
Additional labelStyle
and inputStyle
properties are available to style the respective elements. Please use discretion when adding custom styles.
import React from 'react';import { Checkbox } from 'react-magma-dom';export function Example() {return (<><CheckboxcheckedcontainerStyle={{ border: '1px dotted purple' }}inputStyle={{ boxShadow: '3px 3px 3px rgba(0, 0 , 0, .6)' }}labelStyle={{ color: 'brown', fontStyle: 'italic' }}labelText="Custom styles"/><Checkbox checked labelText="No custom styles" /></>);}
Node as labelText
The labelText
prop can either be a string, or it can be a React Node.
import React from 'react';import { Checkbox } from 'react-magma-dom';export function Example() {const myLabel = (<strong>Node as <i>label</i></strong>);return <Checkbox labelText={myLabel} />;}
Internationalization
Some of the internationalization overrides use placeholders to insert selected values in to the message. Placeholders are specific keywords surrounded by curly braces.
{labelText}
will be replaced with the checkbox'slabelText
.
Full example of internationalization override options
import React from 'react';import {Checkbox,defaultI18n,IndeterminateCheckbox,I18nContext,IndeterminateCheckboxStatus,magma,} from 'react-magma-dom';export function Example() {const [checkedItems, setCheckedItems] = React.useState<Array<boolean>>([true,false,]);const status: IndeterminateCheckboxStatus = checkedItems.every(Boolean)? IndeterminateCheckboxStatus.checked: checkedItems.some(Boolean)? IndeterminateCheckboxStatus.indeterminate: IndeterminateCheckboxStatus.unchecked;function handleUpdateIndeterminateChecked(event: React.ChangeEvent<HTMLInputElement>) {setCheckedItems([event.target.checked, event.target.checked]);}function handleUpdateRedChecked(event: React.ChangeEvent<HTMLInputElement>) {setCheckedItems([event.target.checked, checkedItems[1]]);}function handleUpdateBlueChecked(event: React.ChangeEvent<HTMLInputElement>) {setCheckedItems([checkedItems[0], event.target.checked]);}return (<I18nContext.Providervalue={{...defaultI18n,indeterminateCheckbox: {isCheckedAnnounce:'Custom message about checked status for {labelText} checkbox',isIndeterminateAnnounce:'Custom message about indeterminate status for {labelText} checkbox',isUncheckedAnnounce:'Custom message about unchecked status for {labelText} checkbox',},}}><IndeterminateCheckboxonChange={handleUpdateIndeterminateChecked}status={status}labelText="Colors"/><div style={{ marginLeft: magma.spaceScale.spacing08 }}><Checkboxchecked={checkedItems[0]}onChange={handleUpdateRedChecked}labelText="Red"/><Checkboxchecked={checkedItems[1]}onChange={handleUpdateBlueChecked}labelText="Blue"/></div></I18nContext.Provider>);}
Testing
Passing in the testId
prop will add the data-testid
attribute to the input element for easier querying in tests.
<CheckboxdefaultChecked="{true}"id="customId"labelText="Checkbox"testId="checkbox-id"/>
Checkbox Props
This component uses forwardRef
. The ref is applied to the Checkbox input
element.
All of the standard input attributes can be provided as props and will be applied to the input
element that gets rendered.
checked
Description
If true, element is checked (i.e. selected)
Type
boolean
Default
false
color
Description
Hex code for the background color
Type
string
Default
#3942B0 (theme.colors.primary)
containerStyle
Description
Style properties for the component container element
Type
CSSProperties
Default
-
defaultChecked
Description
If true, checkbox is checked on first render
Type
boolean
Default
-
disabled
Description
If true, element is disabled
Type
boolean
Default
false
errorMessage
Description
Content of the error message for an individual checkbox. If a value is provided, the input will be styled as an error state and the error message will display.
Type
React.ReactNode
Default
-
hasError
Type
boolean
Default
-
inputStyle
Description
Style properties for the checkbox element
Type
CSSProperties
Default
-
isInverse
Description
If true, the component will have inverse styling to better appear on a dark background
Type
boolean
Default
false
isTextVisuallyHidden
Description
If true, label text will be hidden visually, but will still be read by assistive technology
Type
boolean
Default
false
labelStyle
Description
Style properties for the label element
Type
CSSProperties
Default
-
labelText
Description
Content of label; can be node or string
Type
React.ReactNode
Default
-
onChange
Description
Action that fires when selected value of the checkbox changes
Type
function
Default
-
textPosition
Description
Whether the label appears to the left of the right of the checkbox
Type
enum, one of:
CheckboxTextPosition.left
CheckboxTextPosition.right
Default
CheckboxTextPosition.right
On this page