Home > database >  how can I make div tags as much as number in state(react.js)
how can I make div tags as much as number in state(react.js)

Time:10-01

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>

CodePudding user response:

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>
  );
}

CodePudding user response:

return new Array(number).fill(undefined).map((_, key) => <div key={key}></div>);

CodePudding user response:

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

CodePudding user response:

You can even do it without 'Submit' button. See the codesandbox link and the code snippet below:

import "./styles.css";
import * as React from 'react';
import { useState } from 'react';

export default function App() {
  const [divTags, setDivTags] = useState([])
  const appendChilddiv = (e) => {
    const numberAsString = e.target.value;
    let numberDivTags;
    if (numberAsString.length === 0) {
      numberDivTags = 0
    } else {
      numberDivTags = parseInt(numberAsString, 10)
    }
    setDivTags([...Array(numberDivTags)])
    console.log(divTags)
  }
  return (
    <>
      <form className="a">
        <input type="number" onChange={appendChilddiv}/>
      </form>
      <form className="b">
        {divTags.map((e, i) => {
          return <p key={i}>Div number {i}</p>
        })}
      </form>
    </>
  );
}
  • Related