DXC Logo

Checkbox

Checkboxes are inputs that allow the user to select one or more options from a range of attributes.

Props

NameTypeDescriptionDefault
ariaLabelstringSpecifies a string to be used as the name for the checkbox element when no label is provided.'Checkbox'
checkedbooleanIf true, the component is checked. If undefined the component will be uncontrolled and the value will be managed internally by the component.-
defaultCheckedbooleanInitial state of the checkbox, only when it is uncontrolled.false
disabledbooleanIf true, the component will be disabled.false
labelstringText to be placed next to the checkbox.-
labelPosition'before' | 'after'Whether the label should appear after or before the checkbox.'before'
margin'xxsmall' | 'xsmall' | 'small' | 'medium' | 'large' | 'xlarge' | 'xxlarge' | MarginSize of the margin to be applied to the component. You can pass an object with 'top', 'bottom', 'left' and 'right' properties in order to specify different margin sizes.-
namestringName attribute of the input element.-
onChange(value: boolean) => voidThis function will be called when the user clicks the checkbox. The new value will be passed as a parameter.-
optionalbooleanIf true, the component will display the text '(Optional)' next to the label.false
readOnlybooleanIf true, the component will not be mutable, meaning the user can not edit the control.false
refReact.Ref<HTMLDivElement>Reference to the component.-
size'small' | 'medium' | 'large' | 'fillParent' | 'fitContent'Size of the component.'fitContent'
tabIndexnumberValue of the tabindex attribute.0
valuestringWill be passed to the value attribute of the HTML input element. When inside a form, this value will be only submitted if the checkbox is checked.-

Examples

Controlled

() => {
  const [checked, changeChecked] = useState(false);
  const onChange = (newValue) => {
    changeChecked(newValue);
  };

  return (
    <DxcInset space="var(--spacing-padding-xl)">
      <DxcCheckbox label="Of legal age" checked={checked} onChange={onChange} />
    </DxcInset>
  );
}

Uncontrolled

() => {
  const checkboxRef = useRef();

  const handleSubmit = () => {
    const checkbox = checkboxRef.current.getElementsByTagName("input")[0];
    console.log(checkbox.checked ? checkbox.value : "");
  };

  return (
    <DxcInset space="var(--spacing-padding-xl)">    
      <DxcFlex direction="column" gap="var(--spacing-gap-xl)">
        <DxcCheckbox
          label="Of legal age"
          defaultChecked
          value="ofLegalAge"
          ref={checkboxRef}
        />
        <DxcButton
          label="Submit"
          type="submit"
          onClick={handleSubmit}
        />
      </DxcFlex>
    </DxcInset>
  );
}