unregister: (name: string | string[], options) => void
This method allows you to unregister
a single input or an array of inputs. It also provides a second optional argument to keep state after unregistering an input.
Rules
This method will remove input reference and its value which means build-in validation rules will be removed as well.
By
unregister
an input, it will not affect or unregister your schema validation.const schema = yup.object().shape({ firstName: yup.string().required() }); unregister("firstName"); // this will not remove the validation against firstName input
Props
The example below shows what to expect when you invoke the unregister
method.
<input {...register('yourDetails.firstName')} /> <input {...register('yourDetails.lastName')} />
The example below shows what to expect when you invoke the unregister
method.
Type | Input Name | Example |
---|---|---|
string // as key name | unregister("yourDetails") | {} |
string | unregister("yourDetails.firstName") | { lastName: '' } |
string[] | unregister(["yourDetails.lastName"]) | { firstName: '' } |
Options
Name | Type | Description | Code Examples |
---|---|---|---|
keepDirty | boolean |
|
|
keepTouched | boolean |
|
|
keepValid | boolean |
|
|
keepError | boolean | errors will not be updated. |
|
keepValue | boolean | input's current value will not be updated. |
|
keepDefaultValue | boolean | input's defaultValue which defined in useForm will be remained. |
|
import React, { useEffect } from "react"; import { useForm } from "react-hook-form"; export default function App() { const { register, handleSubmit, unregister } = useForm(); const onSubmit = data => console.log(data); React.useEffect(() => { register("lastName"); }, [register]) return ( <form onSubmit={handleSubmit(onSubmit)}> <button type="button" onClick={() => unregister("lastName")}>unregister</button> <input type="submit" /> </form> ); }
import React, { useEffect } from "react"; import { useForm } from "react-hook-form"; interface IFormInputs { firstName: string; lastName?: string; } export default function App() { const { register, handleSubmit, unregister } = useForm<IFormInputs>(); const onSubmit = (data: IFormInputs) => console.log(data); React.useEffect(() => { register("lastName"); }, [register]) return ( <form onSubmit={handleSubmit(onSubmit)}> <button type="button" onClick={() => unregister("lastName")}>unregister</button> <input type="submit" /> </form> ); };