Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
Looping Through Text Inputs in React

I'm building an app where I want the user to specify a number of text fields and then render this amount of fields dynamically. I'm having trouble setting up the state so that it is unique for each field. Here is the code segment:

        var fieldsArray = [];

        for(var i = 0; i <= this.props.numToShow; i ++){
        fieldsArray.push(
            <div>
                <label>
                    <div className="label">{i}</div> 
                    <input type='text' value={this.state.value} name={this.state.value} onChange={this.handleChange} />
                </label>
            </div>
            );
        }

    return (
      <div className = 'inputs'>
        {fieldsArray}
      </div>
    );

Currently, when I change one of the fields, all the other fields update with that unique fields state. Here is the handleChange function that sets the state:

    handleChange: function(e){
       this.setState({
           value: e.target.value,
       });
    }

Is it possible to initialize the state as an array and keep track of the inputs that way? Or is there a better way to do this?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Keeping an array of values in state would work fine. You'll just have to make sure you're passing the index of the input so you know what to update. bind helps with this:

class YourComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { values: [] };
  }

  handleChange(i, e) {
    this.setState({
      values: { ...this.state.values, [i]: e.target.value }
    });
  }

  render() {
    var fieldsArray = [];

    for (var i = 0; i <= this.props.numToShow; i++) {
      fieldsArray.push(
        <div>
            <label>
                <div className="label">{i}</div> 
                <input 
                  type='text' 
                  value={this.state.values[i]} 
                  name={this.state.values[i]} 
                  onChange={this.handleChange.bind(this, i)} />
            </label>
        </div>
      );
    }

    return (
      <div className = 'inputs'>
        {fieldsArray}
      </div>
    );
  }
}
over 4 years ago · Santiago Trujillo Relatório

0



                               onChange={(e) => {
                                    var newPresetList = [...presetList]

                                    newPresetList.map((_item) => {
                                      if (_item.id === item.id) {
                                        _item.preset_name = e.target.value
                                        return
                                      }
                                    })
                                    setPresetList(newPresetList)
                                  }}

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda