Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

react forms Controlled component

I am trying to make a form where inputs fields can be generated dynamically. While running it runs but react throws a warning about not being a controlled component. Any example for the solution I look online uses classes and constructors, is there any other way to do it without using classes?

import { useState } from 'react';

function Try() {
  const [formFields, setFormFields] = useState([
    { StepNo: '', StepDisc: '' },
  ])

  const handleFormChange = (event, index) => {
    let data = [...formFields];
    data[index][event.target.name] = event.target.value;
    setFormFields(data);
  }

  const submit = (e) => {
    e.preventDefault();
    console.log(formFields)
  }

  const addFields = () => {
    let object = {
      StepNo: '',
      StepDiscs: ''
    }

    setFormFields([...formFields, object])
  }

  const removeFields = (index) => {
    let data = [...formFields];
    data.splice(index, 1)
    setFormFields(data)
  }

  return (
    <div className="">
      <form onSubmit={submit}>
        {formFields.map((form, index) => {
          return (
            <div key={index}>
              <input
                name='StepNo'
                placeholder='StepNo'
                onChange={event => handleFormChange(event, index)}
                value={form.StepNo}
              />
              <input
                name='StepDisc'
                placeholder='StepDisc'
                onChange={event => handleFormChange(event, index)}
                value={form.StepDisc}
              />
              <button onClick={() => removeFields(index)}>Remove</button>
            </div>
          )
        })}
      </form>
      <button onClick={addFields}>Add More..</button>
      <br />
      <button onClick={submit}>Submit</button>
    </div>
  );
}

export default Try;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There’s just typo in your code when you initialize new form data when adding. Instead of

let object = {
  StepNo: '',
  StepDiscs: ''
}

It should be

let object = {
  StepNo: '',
  StepDisc: ''
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading