Home > Back-end >  Dynamically add input field React
Dynamically add input field React

Time:10-08

I am trying to add a new row of input directly under the current row. However, I can only add the new input at the bottom of the array instead of directly after the object within the array

  const initialState = [
    { name: "John", Age: 0, height: 0, weight: 0 },
    { name: "Mary", Age: 0, height: 0, weight: 0 },
    { name: "Darren", Age: 0, height: 0, weight: 0 },
    { name: "Eli", Age: 0, height: 0, weight: 0 },

  ];

  const [infoValues, setInfoValues] = useState(initialState);

// I want to add the new row directly under the current one instead at the last

  const addInputRow = () => {
    setInfoValues([
      ...infoValues,
      { name: "Eli", Age: 0, height: 0, weight: 0},
    ]);
  };

  const removeInputRow = (index) => {
    const valueList = [...infoValues];
    valueList.splice(index, 1);
    setInfoValues(valueList);
  };

CodePudding user response:

You're almost there. You're addInputRow method should accept an index, and you would splice the value similar to how you remove:

Note the second splice parameter is 0 - this means "remove 0 items during the splice". The third parameter means "insert this item at the specified index".

  const addInputRow = (index) => {
    const valueList = [...infoValues];
    valueList.splice(index, 0, { name: "Eli", Age: 0, height: 0, weight: 0})
    setInfoValues(valueList);
  };

CodePudding user response:

I bet that the reason why Ryan's answer is not working for you, is that you are not correctly passing the index to the function, because when splice get undefined for the starting point, it will behave like if it is a 0, and add it to the first place.

Check this out, maybe can give you some clarity:

import React, { useState } from "react";

const initialState = [
  { name: "John", Age: 0, height: 0, weight: 0 },
  { name: "Mary", Age: 0, height: 0, weight: 0 },
  { name: "Darren", Age: 0, height: 0, weight: 0 },
  { name: "Eli", Age: 0, height: 0, weight: 0 }
];

export default function App() {
  const [infoValues, setInfoValues] = useState(initialState);

  const addInputRow = (index) => {
    const newInfoValues = [...infoValues];
    newInfoValues.splice(index   1, 0, { name: "Eli", Age: 0, height: 0, weight: 0 });

    setInfoValues(newInfoValues);
  };

  return (
    <div className="App">
      <ul>
        {infoValues.map((value, index) => (
          <li key={index} onClick={() => addInputRow(index)}>
            {value.name}
          </li>
        ))}
      </ul>
    </div>
  );
}
  • Related