Home > Net >  How can i set a default value of input with React hook form?
How can i set a default value of input with React hook form?

Time:08-09

const { register, handleSubmit, watch } = useForm();
<input {...register("title")} type="text" value="I want a default value" />

When input is rendered in DOM i want it to have a default value saying I want a default value

CodePudding user response:

From the docs:

useForm({
  mode: 'onSubmit',
  reValidateMode: 'onChange',
  defaultValues: {},
  resolver: undefined,
  context: undefined,
  criteriaMode: "firstError",
  shouldFocusError: true,
  shouldUnregister: false,
  shouldUseNativeValidation: false,
  delayError: undefined
})

In your code it would work like this:

const { register, handleSubmit, watch } = useForm({
  defaultValues: {
    title: 'I want a default value'
  }
});
<input {...register("title")} type="text" />

CodePudding user response:

Check this out.

const defaultValue = {
 text: "I want a default value."
};

<input
        {...register("title")} type=text
        defaultValue={defaultValue.text}
      />
  • Related