Home > Mobile >  react forms Controlled component
react forms Controlled component

Time:06-28

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;

CodePudding user response:

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: ''
}

CodePudding user response:

You need to change StepDiscs to StepDisc :-)

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