Skip to main content

Switch

A configurable Switch component used to gather user input. Available as an alternative to the Checkbox. The Switch component behaves as a toggle between a checked and unchecked state.

Import

// with @dhl-official/react-library:
import { DhlSwitch } from "@dhl-official/react-library"
// with @dhl-official/ui-libraries/react-library:
import { DhlSwitch } from "@dhl-official/ui-libraries/react-library"

Code

<DhlSwitch>Example Text</DhlSwitch>

Interactive Demo

Migrating from DUIL 1.0

  • Rename onChange to changeEvent
  • Rename disabled to isDisabled
  • Rename color to variant prop

Readme

Usage

Dhl-switch

Snippets of code in HTML and JavaScript to show some of the use cases for the component. The code is not meant to be executed, but to be used as a reference for the usage of the component.
Angular, React and Vue usages are not included in this documentation, but can be easily derived from the html and javascript code.

default usage

<form novalidate>
<dhl-grid-container columns="2">
<dhl-grid-cell span-columns="2">
<dhl-switch
name="switch-3"
value="testing"
>
Example text
</dhl-switch>
</dhl-grid-cell>

<dhl-grid-cell>
<dhl-button
type="reset"
variant="text"
>
reset
</dhl-button>
</dhl-grid-cell>
<dhl-grid-cell>
<dhl-button
type="submit"
variant="primary"
>
submit
</dhl-button>
</dhl-grid-cell>
</dhl-grid-container>
</form>

<script type="module">
const form = document.querySelector("form");

form.addEventListener("submit", async (e) => {
e.preventDefault();
console.log(Object.fromEntries(new FormData(form)));
return await form.checkValidity();
});
</script>

usage with validation (required) and (browser) default validation message

<form novalidate>
<dhl-grid-container columns="2">
<dhl-grid-cell span-columns="2">
<dhl-switch
name="switch-3"
value="testing"
required
>
Example text
</dhl-switch>
</dhl-grid-cell>

<dhl-grid-cell>
<dhl-button
type="reset"
variant="text"
>
reset
</dhl-button>
</dhl-grid-cell>
<dhl-grid-cell>
<dhl-button
type="submit"
variant="primary"
>
submit
</dhl-button>
</dhl-grid-cell>
</dhl-grid-container>
</form>

<script type="module">
const form = document.querySelector("form");

form.addEventListener("submit", async (e) => {
e.preventDefault();
console.log(Object.fromEntries(new FormData(form)));
return await form.checkValidity();
});
</script>

usage with validation (required) and custom validation message

<form novalidate>
<dhl-grid-container columns="2">
<dhl-grid-cell span-columns="2">
<dhl-switch
name="switch-3"
value="testing"
required
>
Example text
</dhl-switch>
</dhl-grid-cell>

<dhl-grid-cell>
<dhl-button
type="reset"
variant="text"
>
reset
</dhl-button>
</dhl-grid-cell>
<dhl-grid-cell>
<dhl-button
type="submit"
variant="primary"
>
submit
</dhl-button>
</dhl-grid-cell>
</dhl-grid-container>
</form>

<script type="module">
const form = document.querySelector("form");
const switchComponent = document.querySelector("dhl-switch");
const validationMessageInvalid = "This field is required";
const validationMessageValid = "This field is valid";

form.addEventListener("submit", async (e) => {
e.preventDefault();
const isValid = await e.target.checkValidity();
if (isValid) {
switchComponent.validation = {
type: "valid",
message: validationMessageValid,
};
} else {
switchComponent.validation = {
type: "invalid",
message: validationMessageInvalid,
};
}
return isValid;
});
</script>

usage with custom events

<form novalidate>
<dhl-grid-container columns="2">
<dhl-grid-cell span-columns="2">
<dhl-switch
required
name="switchComponent-1"
value="testing"
>
Example text
</dhl-switch>
</dhl-grid-cell>

<dhl-grid-cell>
<dhl-button
type="reset"
variant="text"
>
reset
</dhl-button>
</dhl-grid-cell>
<dhl-grid-cell>
<dhl-button
type="submit"
variant="primary"
>
submit
</dhl-button>
</dhl-grid-cell>
</dhl-grid-container>
</form>

<script type="module">
const form = document.querySelector("form");
const switchComponent = document.querySelector("dhl-switch");

const validationMessageInvalid = "This field is required";
const validationMessageValid = "This field valid";
const text = document.querySelector("dhl-text");

const isElementValid = async () => {
const isValid = await switchComponent.checkValidity();
if (isValid) {
switchComponent.validation = {
type: "valid",
message: validationMessageValid,
};
} else {
switchComponent.validation = {
type: "invalid",
message: validationMessageInvalid,
};
}
return isValid;
};

form.addEventListener("submit", async (e) => await isElementValid());

switchComponent.addEventListener("dhlChange", async (e) => await isElementValid());
switchComponent.addEventListener("dhlBlur", async (e) => isElementValid());
switchComponent.addEventListener("dhlFocus", async (e) => isElementValid());
</script>

Properties

PropertyAttributeDescriptionTypeDefault
changeEvent--[DEPRECATED] Use dhlChange event instead

An optional onChange callback handler - see the Example use-case section for implementation example.
(event: InputEvent) => voidundefined
dataAriaDescribedbydata-aria-describedbyAn optional prop defining the list of reference IDs (separated by spaces), recommended when you want to an error message on your field.stringundefined
dataAriaLabeldata-aria-labelAn optional prop defining the text read by the screen reader to represent the component; use this if you need different text to be read from label.stringundefined
dataClassNamedata-class-nameAn optional class name prop for the component.stringundefined
dataIdidAn optional prop. Gives a valid HTML ID attribute value for the component.stringdhl-switch-${getRandomString()}
dataTestiddata-testidAn optional prop. The test id attached to the component as a data-testid attribute.stringundefined
dataTrackingdata-trackingAn optional data tracking prop for the component.stringundefined
isCheckedcheckedAn optional prop used to describe either a toggled or untoggled state of the Switchbooleanfalse
isDisabledis-disabledAn optional flag to define if the component is disabled.booleanundefined
namenameAn optional value to be set to the element HTML name attribute. It takes any valid value that can be used for the name attribute of an HTMLInputElement.stringundefined
requiredrequiredAn optional prop to flag the component as required within a form context.booleanundefined
validation--An optional object to set-up a custom components validation state. Required Fields: message type{ type: Variants.valid \| Variants.invalid \| Variants.note; message?: string; }undefined
valuevalueA REQUIRED prop defining the value of the component which is taken when a form is submitted.stringundefined
variantvariantAn optional prop to select a component design variant."primary" \| "secondary"DHL_SWITCH.VARIANT.PRIMARY

Events

EventDescriptionType
dhlBlurEvent emitted when the component loses focus.CustomEvent<{ value: string; checked: boolean; }>
dhlChangeEvent emitted when the component changes value.CustomEvent<{ value: string; checked: boolean; }>
dhlFocusEvent emitted when the component receives focus.CustomEvent<{ value: string; checked: boolean; }>

Methods

checkValidity() => Promise<boolean>

Checks the validity of the component.

Returns

Type: Promise<boolean>

A promise that resolves to true if the component is valid, otherwise false.

getInputElement() => Promise<HTMLInputElement>

Retrieves the input element asynchronously.

Returns

Type: Promise<HTMLInputElement>

A promise that resolves to the input element.

getValidationMessage() => Promise<string>

Retrieves the validation message for the component.

Returns

Type: Promise<string>

A promise that resolves to a string representing the validation message.

reportValidity() => Promise<boolean>

Reports the validity of the component.

Returns

Type: Promise<boolean>

A promise that resolves to a boolean indicating whether the component is valid.

setValidity(validity: ValidityState, validationMessage?: string) => Promise<void>

Sets the validity state of the component.

Parameters

NameTypeDescription
validityValidityState- The validity state to set.
validationMessagestring- An optional validation message to set.

Returns

Type: Promise<void>

A Promise that resolves when the validity state is set.

willValidate() => Promise<boolean>

Returns a promise that resolves to true if the element will successfully validate, or false otherwise.

Returns

Type: Promise<boolean>

A promise that resolves to a boolean value indicating whether the element will validate.

Slots

SlotDescription
"unnamed"unnamed children slot for text that accompanies the DhlSwitch

Dependencies

Depends on

Graph


Built by DHL User Interface Library Team!