简体   繁体   中英

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>

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM