[Solved] Ion Select Selected Option

Today I was auto filling a form, and noticed that if I put selected on the option it doesn’t actually show it as selected, but if you click into the select drop down it is selected, and when I click “ok” it displays correctly. Am I doing this correctly? adopting is set to whatever passes through to the component.


function getDogOptions(dogs) {
    const data = dogs.map((el, index) => {
      return (<IonSelectOption value={el.id} key={index}>{el.name}</IonSelectOption>);
    });
    return data;
 }
....
<IonSelect placeholder="Select a Dog" name="dog_1" onIonChange={e => updateForm(e, 'dog_1') }>
     { doggies && getDogOptions(doggies) }
</IonSelect>

I decided to reduce the code so that the three options didn’t all have a pre-selected dog, however that seemed to fix my problem. If anyone knows why it caused a problem I’d love to hear about it.


  function getDogOptions(dogs, input) {
    return (
      <IonSelect placeholder="Select a Dog" name={input} onIonChange={e => updateForm(e, input) }>
        {
          dogs.map((el, index) => {
            return (<IonSelectOption value={el.id} key={index} selected={adopting === el.id && input === 'dog_1'}>{el.name}</IonSelectOption>);
          })
        }
      </IonSelect>
    );
  }

You can also use the value property of IonSelect to set a value. Here’s an example:

function App() {
  const INITIAL = "dog2";
  const [value, setValue] = React.useState(INITIAL);
  const options = ["dog1", "dog2", "dog3"];
  return (
    <IonItem>
      <IonLabel>Select a Dog</IonLabel>
      <IonSelect value={value} onIonChange={e => setValue(e.detail.value)}>
        {options.map((option, i) => (
          <IonSelectOption value={option} key={i}>
            {option}
          </IonSelectOption>
        ))}
      </IonSelect>
    </IonItem>
  );
}

As long as INITIAL is one of the options, it will be displayed as selected.