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

206
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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