UseController
This custom hook powers Controller. Additionally, it shares the same props and methods as Controller. It's useful for creating reusable Controlled input.
Props
The following table contains information about the arguments for useController.
| Name | Type | Description |
|---|---|---|
| control | Object | control object is from invoking createForm. Optional when using FormProvider. |
| name | string | Unique name of your input. |
| rules | Object | Validation rules in the same format for register options, which includes: required, min, max, minLength, maxLength, pattern, validate |
Returns
The following table contains information about properties which useController produces.
| Name | Type | Description |
|---|---|---|
| field.value | Accessor | Signal to retrieve the current value of the controlled component. |
| field.name | string | Input's name being registered. |
| field.onInput | Function | A function which sends the input's value to the library. |
| field.onChange | Function | A function which sends the input's value to the library. |
| field.ref | Function | A ref used to connect hook form to the input. Assign ref to component's input ref to allow hook form to focus the error input. |
| fieldState.error | Accessor | Signal to retrieve the error for this specific input. |
Using Hooks API
import { TextField } from "@kobalte/core/text-field"
import { createForm, useController } from "solid-hook-form"
const ControlledInput = (props) => {
const { field, fieldState } = useController({
control: props.control,
name: "firstName",
rules: { required: true }
})
return (
<TextField>
<TextField.Label>Field</TextField.Label>
<TextField.Input
{...field}
value={field.value()}
validationState={fieldState.error() ? "invalid" : "valid"}
/>
</TextField>
)
}
export const ExampleForm = () => {
const form = createForm({
defaultValues: {
firstName: ""
},
mode: "onChange"
})
const { control, handleSubmit } = form
const onSubmit = (values) => {
console.log(values)
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
<ControlledInput control={control} />
<button type="submit">Save</button>
</form>
)
}