Dynamic form is not working properly on click of add

Viewed 113

I am creating a dynamic form where I have on click of add creating a new element every time, it is working fine till here.

  • I have a save button on click I am getting all the data and need to do the further process.
  • When I click on save I am doing the validation using React-hook-form.
  • So first time when the fields are empty I click on save and it shows the error (fields can not be empty)
  • Then when I type inside the input field it is not taking the first character I press it is taking the second one.
  • Same happens when I click backspace after typing a word, the last character it is not deleting.

What I am doing

  • Below is my onchange, I am passing three things, e,index and name

     const handleInputChange = (e, index, name) => {
     const { value } = e.target;
     console.log(name);
     const list = [...inputList];
     list[index][name] = value;
     setInputList(list);};
    
  • My HTML

     < input
       type = "text"
       placeholder = "Display Name"
       name = {
         `employees[${i}].firstName`
          }
       className = {
         errors.employees &&
         errors.employees[i] &&
         errors.employees[i].firstName ?
         'form-control error_input' :
         'form-control'
       }
       onChange = {
         (e) => handleInputChange(e, i, 'firstName')
      }
        value = {
         li.firstName
         }
       ref = {
      register({
         required: 'First Name is required',
      })
    }
    

    />

The issue

  • Click on Save first time when Input field is empty.

  • Type Test -- it wont take t as first time need to press t two times

  • Once Test is typed press backspace to delete it will delete tes but to delete T need to press two times.

I just want to know what is the issue, The code I have written I think I have not missed anything.

My working code

3 Answers

just need to focus on the input if the Input field is empty.

In your react component create one more handler for save

 const handleSave = () => {
    const name_field = document.getElementById("name_field");
    const nameVal = name_field.value;
    if (nameVal.toString().trim().length < 1) {
      name_field.focus();
    }
  };

demo link https://codesandbox.io/s/objective-breeze-hhlfqx?file=/src/App.js

It is hard to debug without the complete code. You are missing to expose the values of errors, i', employees`, and that 'Save' feature. As it is, I can't reproduce the issue.

Having said so, you might want to re-consider using indexes to identify elements in an array. Elements can shift positions, so usually, you will have inside each object a unique id and employ a .find() or .filter() to track the correct element, which is less prone to mistakes.

Related