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

188
Visualizações
ReactJS - As can I generate several form fields with value properties sharing the same names but not the same values?

After 2 days of fierce struggles, I decided to post for the first time on Stack Overflow :).

My concern is the following:

As part of a project, I want to generate a number of input fields equal to the size of an array. Example :

function App() {
  const [UseState, setUseState] = useState("");
  const array = [0, 1, 2];

  const HandleAdding = (e) => {
    e.preventDefault;
    const returnJson = { UseState };
    //rest of the code
  };

  return (
    <div>
      {array.map(() => (
        <form onSubmit={HandleAdding}>
          <input value={UseState} onChange={(e) => setUseState(e.target.value)} />
        </form>
      ))}
    </div>
  );
}

We can already know the problem, when inserting a value on a field, this same value will be inserted on all the other fields which share the same UseState as value. For even more concrete, here is an illustration of the problem on CodeSandBox:

https://codesandbox.io/s/adoring-rgb-n0bdk?file=/src/App.js

So try to fill in a field and you will notice the problem. I tried a lot of things to solve my problem like this:

https://codesandbox.io/s/blissful-rain-mcol2?file=/src/App.js (I'm trying to adapt the code in order to solve my problem).

I do not put anything more to prevent it from becoming too long. So, would you have a solution to solve the problem? For my part I am short of ideas, and still a beginner on React. Thanks in advance! ^^

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

function App() {
  const [UseState, setUseState] = useState({});
  const array = [0, 1, 2];
  const size = array.length;

  const HandleAdding = (e) => {
    e.preventDefault;
    const returnJson = { UseState };
    //rest of the code
  };

  return (
    <div>
      {array.map((x) => (
        <form onSubmit={HandleAdding}>
          <input value={UseState[x]} onChange={(e) => setUseState({...UseState, [x]: e.target.value})} />
        </form>
      ))}
    </div>
  );
}

You can easily solve the problem by changing the structure of UseState to become an object with the pattern below

UseState = {
  0: 'Isaac',
  1: 'James',
  2: 'John'
}

You need to store multiple value, so when you retrieve for value, use UseState[x], and when you update, you need to spread the object and update the value of a particular properties

about 4 years ago · Juan Pablo Isaza Relatório

0

  1. Generally, for forms, you hold the values of the inputs in one object in state, and then update that state with the new values when the input has been changed.

  2. At the moment you're creating more forms than you need. You don't even need the form element because the input elements doesn't actually require it.

  3. Initialise your state with an object.

  4. map over the array instead of the length of the array.

  5. Name your inputs so when the values change you can easily update the state.

const { useState } = React;

function Example() {

  // Initialise state with an object
  const [ data, setData ] = useState({});

  // Example input names
  const arr = ['name', 'address', 'number'];

  // When the input changes, get the name
  // and the value, and update the state using
  // that information
  function handleChange(e) {
    const { name, value } = e.target;
    setData({ ...data, [name]: value });
  }

  function handleSubmit() {
    console.log(data);
  }

  function createInputs(arr) {

    // `map` over the array and return some JSX
    return arr.map(el => {
      return (
        <label>{el.toUpperCase()}:&nbsp;
          <input type="text" name={el} />
        </label>
      );
    });
  }

  return (
    <div onChange={handleChange}>
      {createInputs(arr)}
      <button onClick={handleSubmit}>Submit</button>
    </div>
  );
};

// Render it
ReactDOM.render(
  <Example />,
  document.getElementById("react")
);
label { display: block; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>

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