Switch
The Switch
component allows users to toggle between two different states. You
can set a specific initial value using the defaultValue
prop for an
uncontrolled switch or setting the initial value of the state of a controlled
switch accordingly. The name
prop also needs to be specified for identifying
the Switch
when submitting it in a form.
Import
import { Switch } from '@dynatrace/strato-components-preview/forms';
Use cases
Control the state
The Switch
can also be controlled, meaning that you can handle the state. To
do so, you need to use the onChange
prop to provide a handler that is called
when the internal state of the Switch
changes. You also need to assign the
value from the state to the Switch
by setting the on
prop.
Validate
This example shows how you can validate the Switch
using the react-hook-form
package, which handles error messages. For connecting the form with the Switch
and validating, you need to register the field with custom error messages and
use the useForm
hook from react-hook-form
. Also, by using the controlState
prop, you can override the error messages and connect the Switch
's error state
and message to that of the form. This shows a hint in case of an error and
applies proper styling to the component.
Props
SwitchProps
Signature:
export declare type SwitchProps = & ( | );
SwitchBaseProps
, , , , ,
Name | Type | Default | Description |
---|---|---|---|
formValue? | - | The string used as the value of the switch when submitting it in a form, if the switch is toggled on. | |
disabled? | false | Whether the switch is disabled or not. If true, the switch cannot be clicked in order to toggle its state. | |
required? | false | Whether the switch is required or not. If true, the switch is marked with an asterisk. |
SwitchControlledProps
Name | Type | Default | Description |
---|---|---|---|
value | - | Whether the switch is on or off. | |
onChange | (checked: , event?: <>) => | - | Handler that is called when the 'on' attribute changes. |
name? | - | The name used for the switch, that identifies it when submitting it in a form. |
SwitchUncontrolledProps
Name | Type | Default | Description |
---|---|---|---|
defaultValue? | false | The default on or off state. | |
name | - | The name used for the switch button, that identifies it when submitting it in a form. |