1

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>
  );
}```
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43

2 Answers2

1

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>
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
  • It worked for me. Thanks! But I didn't understand what's the difference if I do not use the temp array made by shallow copy using slice() method and instead use the inputFields array only? – curious_Coder Apr 26 '22 at 11:05
  • @curious_Coder This answer might be useful https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-react-js – Anurag Srivastava Apr 26 '22 at 11:07
  • @curious_Coder Also, this one: https://stackoverflow.com/questions/37755997/why-cant-i-directly-modify-a-components-state-really – Anurag Srivastava Apr 26 '22 at 11:09
  • But I am not using arr.push for adding new array elements. I am using spread operator only, as suggested in the answers. – curious_Coder Apr 26 '22 at 11:47
  • I am sorry, I think I was not able to make my question clear. My question was why to create this temp array- const temp = inputFields.slice() , length = temp.length - 1 , { name, age } = temp[length] I used- const { name, age } = inputFields[inputFields.length - 1]; let newField = { name, age }; setInputFields([...inputFields, newField]); ....and it worked as expected. – curious_Coder Apr 26 '22 at 11:48
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"
/>
    
Ismailp
  • 2,333
  • 4
  • 37
  • 66