Trying to edit a dynamically created input field gets deleted

I am creating a new input field onClick of a button. The default state of the input is readonly. However, I have an edit button near it to enable the field to be not readonly. When I click the button, the field gets deleted. Please advise.

This is what I have.

  import React, { useReducer } from "react";
  import "./styles.css";
  import { get, uniqueId, cloneDeep, map } from "lodash";

  const initialState = {
    fields: []
  };

  export default function App() {
const [state, setState] = useReducer(
  (state, newState) => ({
    ...state,
    ...newState
  }),
  initialState
);

const handleEdit = (i) => {
  const fieldsListClone = cloneDeep(state.fields);
  const result = map(fieldsListClone, (item) => {
    if (item.id === i) {
      item.editable = true;
    }
    return item;
  });

  setState({
    fields: result
  });
};

const addNewField = () => {
  const numFields = state.fields.length + 1;
  const renderFieldInput = (i) => {
    const field = state.fields.find((item) => item.id === i);
    return (
      <div key={uniqueId()} style={{ display: "flex" }}>
        <div style={{ border: "1px solid red", marginRight: "20px" }}>
          {i + 1}
        </div>
        <div>
          <input readOnly={!get(field, "editable") || true} />
        </div>
        <div>
          <button onClick={() => handleEdit(i)}>Edit</button>
        </div>
      </div>
    );
  };
  const fieldInputs = [];
  for (let i = 0; i < numFields; i++) {
    fieldInputs.push({
      id: i,
      field: renderFieldInput(i),
      editable: false
    });
  }
  setState({
    fields: fieldInputs
  });
};
return (
  <div className="App">
    {state.fields.map((item) => (
      <div key={uniqueId()}>{item.field}</div>
    ))}
    <button onClick={addNewField}>Add new field</button>
  </div>
);

}

This is my codesandbox link.

Is there a better way to create new form fields? My idea is to store all the properties of the field in a single state value including the editable field as well as the value field.

89 thoughts on “Trying to edit a dynamically created input field gets deleted”

Leave a Comment