Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

77
Vistas
How to use selected attribute of select tag in a loop in React

It is easy when we have individual options like this:

<select name="phone_type" id="phone_type">
  <option value="mobile" selected>Mobile</option>
  <option value="home">Home</option>
  <option value="office">Office</option>
</select>

But in my case I'm doing this using a loop:

phoneTypes = ['Mobile', 'Home', 'Office'];
...
<select onChange={(e) => this.handleChangePhonetype(e, index)}>
  {this.phoneTypes.map((phoneType, index) => {
    return (
      <option key={index} value={phoneType} name="type">
        {phoneType}
      </option>);
   })}
</select>

I searched the internet but couldn't get a proper answer for React. I want 'Mobile' to be selected already when the page loads. I don't know how to do this in React. Please pitch in.

Here is the stackblitz.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You should simply use the type of each phone object as the value to the select element.

Here's the updated stackblitz.

const PhoneTypes = ['Mobile', 'Home', 'Office'];

class Questionnaire extends Component {
  state = {
    phones: [{ type: 'Mobile', number: '' }],
  };

  addContact() {
    this.setState((prevState) => ({
      phones: [...prevState.phones, { type: 'Mobile', number: '' }],
    }));
  }

  handleChange({ target: { name, value } }, phoneIndex) {
    this.setState((prevState) => ({
      phones: prevState.phones.map((phone, index) =>
        phoneIndex === index ? { ...phone, [name]: value } : phone
      ),
    }));
  }

  handleRemove(phoneIndex) {
    this.setState((prevState) => ({
      phones: prevState.phones.filter((_, index) => phoneIndex !== index),
    }));
  }

  handleSubmit(e) {
    console.log(this.state, '$$$');
  }

  render() {
    return (
      <div>
        <h1>The Form</h1>
        <label>Contact</label>
        {this.state.phones.map((phone, index) => {
          return (
            <div key={index}>
              <input
                onChange={(e) => this.handleChange(e, index)}
                value={phone.number}
                name="number"
              />
              <select
                name="type"
                value={phone.type}
                onChange={(e) => this.handleChange(e, index)}
              >
                {PhoneTypes.map((phoneType, index) => {
                  return (
                    <option key={index} value={phoneType}>
                      {phoneType}
                    </option>
                  );
                })}
              </select>
              <button onClick={(e) => this.handleRemove(index)}>Remove </button>
            </div>
          );
        })}
        <hr />
        <button onClick={(e) => this.addContact(e)}>Add contact</button>
        <hr />
        <button onClick={(e) => this.handleSubmit(e)}>Submit</button>
      </div>
    );
  }
}

I also fixed some other issues like mutating the state, incorrect arg to remove function etc.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda