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

199
Visualizações
How to pre-populate fields on click of a button in react?

I am trying to pre-populate the form fields, that are replicated, from the fields that are already filled. On clicking the "Add fields" button, the fields are getting replicated. But I want them to get pre-populated using the data filled in the already existing fields.

From where can I get hold of the input values?

import './style.css';

export default function App() {
  const [inputFields, setInputFields] = useState([{ name: '', age: '' }]);

  const addFields = (e) => {
    e.preventDefault();

    let newField = { name: "", age: '' };
    setInputFields([...inputFields, newField]);
  };

  const handleFormChange = (index, e) => {
    let data=[...inputFields];
    data[index][e.target.name]=[e.target.value];
    setInputFields(data);
  }

  return (
    <div>
      <form>
        {inputFields.map((input, index) => {
          return (
            <div key={index}>
              <input
                type="text"
                name="name"
                placeholder="Enter name"
                value={input.name}
                onChange={(e)=>handleFormChange(index, e)}
              />
              <input
                type="number"
                name="age"
                placeholder="Enter Age"
                value={input.age}
                onChange={(e)=>handleFormChange(index, e)}
              />
              <br />
              <br />
            </div>
          );
        })}
        <button onClick={addFields}>Add Field</button>
        <br />
      </form>
    </div>
  );
}```
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You will need to track changes in input with an onChange handler.

Also, you are not setting values from the last input fields anywhere to be able to duplicate them. The below code might work as you expect:

const { useState } = React;

function App() {
  const [inputFields, setInputFields] = useState([{ name: '', age: '' }]);

  const addFields = (e) => {
    e.preventDefault();
    const temp = inputFields.slice()
    , length = temp.length - 1
    , { name, age } = temp[length]
    
    // Set value from last input into the new field
    let newField = { name, age }
    setInputFields([...temp, newField])
  }
  , handleChange = (index, event) => {
    const temp = inputFields.slice() // Make a copy of the input array first.
    inputFields[index][event.target.name] = event.target.value // Update it with the modified values.
    setInputFields(temp) // Update the state.
  };

  return (
    <div>
      <form>
        {inputFields.map((input, index) => {
          return (
            <div key={index}>
              <input
                onChange={e => handleChange(index, e)}
                value={input.name}
                type="text"
                name="name"
                placeholder="Enter name"
              />
              <input
                onChange={e => handleChange(index, e)}
                value={input.age}
                type="number"
                name="age"
                placeholder="Enter Age"
              />
              <br />
              <br />
            </div>
          );
        })}
        <button onClick={addFields}>Add Field</button>
        <br />
      </form>
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

You have to set the value property on the input field to populate, e.g:

<input
  value={input.name}
  type="text"
  name="name"
  placeholder="Enter name"
/>
    
about 4 years ago · Juan Pablo Isaza 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