Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

189
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda