reactjshtml-selectreact-hook-form

React option selected property doesn't work


I want to set male value as selected by default but its not working.

<select {...register("gender")} className="form-select input" id="gender">
  <option value="Male" selected>{t("signUpPage.male")}</option>
  <option value="Female">{t("signUpPage.female")}</option>
</select>

Solution

  • Since you are using register it seems like you are using react-hook-form. With react-hook-form we can set default values with the useForm hook.

    So in your code, wherever you are calling useForm you would do this.

    const methods = useForm({defaultValues:{gender:"Male"})
    

    I use methods here as a convention because I am not sure what you may be destructuring from useForm, if anything.

    Also if you plan to take advantage of isDirty available on formState it is suggested that you set default values for all the form properties.