skip to Main Content

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>

2

Answers


  1. The issue is that React doesn’t work well with the selected attribute in tags because it handles state differently from plain HTML. Instead of using selected, you need to set the default value of the select element directly using the defaultValue or value prop.

     <select {...register("gender")} className="form-select input" id="gender" defaultValue="Male">
      <option value="Male">{t("signUpPage.male")}</option>
      <option value="Female">{t("signUpPage.female")}</option>
    </select>
    
    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search