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.
Props
The example below shows what to expect when you invoke the unregister
method.
<input {...register('yourDetails.firstName')} /> <input {...register('yourDetails.lastName')} />
Type | Input Name | Value |
---|---|---|
string | unregister("yourDetails") | {} |
string | unregister("yourDetails.firstName") | { lastName: '' } |
string[] | unregister(["yourDetails.lastName"]) | '' |
Options
Name | Type | Description | Code Examples |
---|---|---|---|
keepDirty | boolean |
|
|
keepTouched | boolean |
|
|
keepIsValid | 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. |
|
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 the schema validation.const schema = yup.object().shape({ firstName: yup.string().required() }).required(); unregister("firstName"); // this will not remove the validation against firstName input
Make sure you unmount that input which has
register
callback or else the input will get registered again.const [show, setShow] = React.useState(true) const onClick = () => { unregister('test'); setShow(false); // make sure to unmount that input so register not invoked again. } {show && <input {...register('test')} />}
Examples
import React, { useEffect } from "react"; import { useForm } from "react-hook-form"; export default function App() { const { register, handleSubmit, unregister } = useForm(); React.useEffect(() => { register("lastName"); }, [register]) return ( <form> <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> ); };
Video
The following video explain unregister
API in detail.
Thank you for your support
If you find React Hook Form to be useful in your project, please consider to star and support it.