Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
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;
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

It's not related to the error you have, but I suggest you bind the key to a unique key as it can generate unpredictable issues when you remove the items.

const addFields = () => {
      // Id should has a unique a id to be used in as a key.
      const id = generateUniqueKey()
      let object = {
        StepNo: '',
        StepDiscs: '',
        id
      }

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


{formFields.map((form, index) => {
      return (
        <div key={form.id}>
          <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>
      )
    })}
about 4 years ago · Juan Pablo Isaza Relatório

0

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: ''
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You need to change StepDiscs to StepDisc :-)

  const addFields = () => {
    let object = {
      StepNo: '',
      StepDiscs: ''
    }
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda