Search code examples
ionic-frameworkionic5ionic-react

Set default value of ion-select in React / Ionic 5


I created a React app with Ionic 5 and I want to set the default value of a select element that is shown in a form.

This SO question is all about Angular, but I need to do this in React.

Here's my select code:

    <IonSelect id="category" name="group" ref={register}>
      <IonSelectOption key="noGroup" value="noGroup">No group</IonSelectOption>
      <IonSelectOption key="addTerm" value="addTerm">Add a group</IonSelectOption>
      {
        termList.map((item) => (
          <IonSelectOption key={item.id} value={item.id}>{item.name}</IonSelectOption>
        ))
      }
    </IonSelect>

I want to set the default value of this select to noGroup when the page is loaded. How can I do that?

The ion-select documentation does not have any information on this.


Solution

  • The default value is specified in the IonSelect tag as such:

      <IonSelect id="category" name="group" ref={register} value={noGroup}>
    

    You can see it in the docs:

            <IonSelect value={hairColor} okText="Okay" cancelText="Dismiss" onIonChange={e => setHairColor(e.detail.value)}>
                  <IonSelectOption value="brown">Brown</IonSelectOption>
                  <IonSelectOption value="blonde">Blonde</IonSelectOption>
                  <IonSelectOption value="black">Black</IonSelectOption>
                  <IonSelectOption value="red">Red</IonSelectOption>
                </IonSelect>
    

    Also as a side note, just in case you still haven't spotted it, it usually helps to see the code of the provided example on the top right, which you can do by clicking the View Source.