react-hook-form: How to remove the data values if the components are not rendered?

Viewed 1048
const onSubmit = data => console.log(data);

<form onSubmit={handleSubmit(onSubmit)}>
    <input defaultValue="test001" {...register("var001")} />
    {somecondition && (
        <>
            <input defaultValue="test002" {...register("var002")} />
            <input defaultValue="test003" {...register("var003")} />
        </>
    )}
  <input type="submit" />
</form>

I have the following react hook form.

I want console.log(data) to print only of the rendered elements.

So if somecondition is not true

I want to see in console.log(data)

data = {
     "var001": "test001"
}

So if somecondition is true

I want to see in console.log(data)

data = {
     "var001": "test001"
     "var002": "test002",
     "var003": "test003",
}

How can i do this

https://codesandbox.io/s/react-hook-form-get-started-forked-55q98

showing the image

enter image description here

2 Answers

You can set shouldUnregister to true to tell RHF to remove the field if the component is unmounted. This property was removed in v7 initially but get added again in the newer version so you need to update RHF to the latest version 7 to use it:

npm i react-hook-form@latest
const { register, handleSubmit, watch } = useForm({
  defaultValues: {
    var001: 'test001',
    var002: 'test002',
    var003: 'test003',
  },
  shouldUnregister: true,
});

Codesandbox Demo

You can add all the fields you want to display if the condition is true in the array. Then it will be convenient to manipulate them and unregister needed fields if condition is false in setShow function. I wrote example for you.

Demo

Related