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
how can I make div tags as much as number in state(react.js)

I'm developing with React.js and below is a simplified version of my component. As you can see, when I click the button state(number) would get a number. And here is what I want, make div tags as much as a number in state(number) in the form tag(which its class name is 'b').

Could you tell me how to make this possible? Thanks for reading. Your help will be appreciated.

//state
const[number,setNumber] = useState('')

//function
const appendChilddiv =(e)=>{
 e.preventDefault()
 setNumber('')
}
<div>
<form className="a" onSubmit={appendChilddiv}>
 
 <input
 value={number}
 onChange={(e)=>setNumber(e.target.value)}
 type="number"/>
 <button type="submit">submit</button>

</form>

<div>
<form className="b">

</form>

</div>

</div>
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

I've created a codesandbox which includes the following code, previously you were storing the value as a string, it'd be best to store it as number so you can use that to map out, which I do via the Array() constructor (this creates an array of a fixed length, in this case the size of the divCount state - when we update the state by changing the input value this creates a re-render and thats why the mapping is updated with the new value)

import "./styles.css";
import * as React from "react";

export default function App() {
  //state
  const [divCount, setDivCount] = React.useState(0);
  //function
  const appendChilddiv = (e) => {
    e.preventDefault();
    // Submit your form info etc.
    setDivCount(0);
  };

  return (
    <div>
      <form className="a" onSubmit={appendChilddiv}>
        <input
          value={divCount}
          onChange={(e) => setDivCount(Number(e.target.value))}
          type="number"
        />
        <button type="submit">submit</button>
      </form>

      <div>
        <form className="b">
          {Array(divCount)
            .fill(0)
            .map((x, idx) => (
              <div key={idx}>Div: {idx + 1}</div>
            ))}
        </form>
      </div>
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can do the following.

First thing it does is creates a new array of some length number.

Next, it fills that array with undefined, because creating new arrays like this doesn't really create an array of that length.

Lastly, we map over this array, we use the index as our key. We return an empty div for each item in the array.

Note, using an index as a key isn't the best idea. In general it should be something as unique as possible. If you have data you can use that is unique, then you should use that as a key.

return new Array(number).fill(undefined).map((_, key) => <div key={key}></div>);
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can map over an array whose length is same as that entered in input & create divs (if number entered is valid):

{!isNaN(number) &&
              parseInt(number, 10) > 0 &&
              Array(parseInt(number, 10))
                .fill(0)
                .map((_, idx) => <div key={idx}>Hey!</div>)
}
  1. isNaN checks is number is valid
  2. parseInt(number, 10) converts string into number,
  3. Array(n) creates a new array with n elements (all empty) (try console logging Array(5)) - so you need to fill it
  4. .fill(n) fill the array (make each element n)
  5. and map is used to render different elements from existing things

So, in this way, you can achieve the mentioned result.

Here's a link to working Code Sandbox for your reference

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