-
Notifications
You must be signed in to change notification settings - Fork 6
2.1 useInertiaInput
Avram Walden edited this page May 22, 2024
·
11 revisions
Provides methods for binding an input to a data value.
This hook will only work within the React Context created by the Form
component.
interface UseInertiaInputProps {
name: string
model?: string
errorKey?: string
strategy?: InputStrategy
clearErrorsOnChange?: boolean
}
Prop | Description |
---|---|
name |
Required value used as the lookup key for getting and setting values on the form data object |
model |
When left empty (default), this component utilizes the model prop from the Form component as the lookup string. Alternatively, if a value is provided, it will use that value as the root level lookup string instead. For instance, if the model prop of the Form is set to 'user' and the name value of the input is 'first_name' , the input values will be assigned to 'user.first_name' . However, if a value is provided to the model in the input, that value will be used as the top-level reference for dot notation, effectively replacing 'user' . |
errorKey |
Can be used to override how errors are stored in the errors object on the form data. (Very unlikely to need to set this) |
strategy |
If you want more control over how inputId and inputName are generated, you can pass your own InputStrategy .The default strategy builds a standard dot-notation string using the form's context and the name value passed to the hook for inputName , and a snake-case string for the inputId . (Very unlikely to need to set this) |
clearErrorsOnChange |
Defaults to true . Set to false to prevent errors being cleared when the input value is changed. Useful if you want control over when an input's errors are cleared, such as with front-end validation. |
While this hook can be used inline to create inputs on the fly, it's intended use is to create reusable input components.
import { useInertiaInput } from 'use-inertia-form'
interface TextInputProps {
name: string
model?: string
label: string
}
const TextInput = ({ name, model, label }: TextInputProps) => {
const { inputName, inputId, value, setValue, error } = useInertiaInput<string>({ name, model })
return (
<label for={ inputId }>{ label }</label>
<input
type='text'
id={ inputId }
name={ inputName }
value={ value }
onChange={ e => setValue(e.target.value) }
>
{ error && <div className="error">{ error }</div> }
)
}
This can then be used within a Form
import { Form } from 'use-inertia-form'
import { TextInput } from '/Components'
const EditUserForm = ({ user }: Schema.User) => {
return (
<Form to={ `users/${user.id}` } model="user" data={ { user } } filter="user.id">
{/* Sync values to `form.data.user.firstName` */}
<TextInput name="firstName" label="First Name" />
</Form>
)
}