简体   繁体   中英

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

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

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" />

Check this out.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM