Checkbox

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

Props

NameTypeDescriptionDefault
defaultCheckedbooleanInitial state of the checkbox, only when it is uncontrolled.false
checkedbooleanIf true, the component is checked. If undefined the component will be uncontrolled and the value will be managed internally by the component.false
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.-
labelstringText to be placed next to the checkbox.-
labelPosition'before' | 'after'Whether the label should appear after or before the checkbox.'before'
namestringName attribute of the input element.-
disabledbooleanIf true, the component will be disabled.false
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
onChange(value: boolean) => voidThis function will be called when the user clicks the checkbox. The new value will be passed as a parameter.-
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.-
size'small' | 'medium' | 'large' | 'fillParent' | 'fitContent'Size of the component.'fitContent'
tabIndexnumberValue of the tabindex attribute.0
refReact.Ref<HTMLDivElement>Reference to the component.-

Examples

Controlled

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

  return (
    <DxcInset space="2rem">
      <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="2rem">    
      <DxcFlex direction="column" gap="2rem">
        <DxcCheckbox
          label="Of legal age"
          defaultChecked
          value="ofLegalAge"
          ref={checkboxRef}
        />
        <DxcButton
          label="Submit"
          type="submit"
          onClick={handleSubmit}
        />
      </DxcFlex>
    </DxcInset>
  );
}