Toggles are controls that are used to quickly switch between two possible states.
import { Toggle } from "@wfp/react"
Make sure to use the toogle in a controlled context.
<Toggle labelText="The Input" helperText="Optional helperText" labelA="Off" labelB="On" name="input-example" />;
This example shows how to use the Toggle component with react-hook-form.
const FormExample = () => { const [defaultValues, setDefaultValues] = useState( {} ); const { control, register, handleSubmit, watch, reset, } = useForm({ defaultValues }); const [data, setData] = useState({}); const setDefaultValuesFunc = (e) => { console.log(e.target.value); try { const values = JSON.parse(e.target.value); setDefaultValues(values); } catch (e) { console.log(e); } }; const resetInputs = () => { reset(defaultValues); }; const currentValues = watch(); return ( <> <form onSubmit={handleSubmit((data) => setData(data) )} > <> <Toggle labelText="The uncontrolled Input" helperText="Optional helperText" labelA="Off" labelB="On" {...register("inputname")} /> <Controller name="inputnameB" control={control} render={({ field }) => { return ( <Toggle labelText="The controlled Input" helperText="Optional helperText" labelA="Off" labelB="On" {...field} onChange={(e) => field.onChange(e.target.checked) } checked={field.value === true} /> ); }} /> </> <Button type="submit">Submit</Button>{" "} <Button onClick={resetInputs} kind="secondary"> Reset here </Button> <div className="debug"> <h4>Submitted form data</h4> <pre>{JSON.stringify(data, null, 2)}</pre> <h4>Current values</h4> <pre> {JSON.stringify(currentValues, null, 2)} </pre> <TextInput labelText="Default values (editable)" defaultValue={JSON.stringify( defaultValues )} onChange={setDefaultValuesFunc} /> </div> </form> </> ); }; render(<FormExample />);
The Toogle component is wrapped inside the Input
component, but can be used without label
or helperText
:
<Toggle labelA="Off" labelB="On" />;