简体   繁体   中英

reactJS - JSX map array to form elements but group each four elements

I wanna create a form with around 30 elements with semantic-ui like this:

     <Form.Input
        id="survive"
        type="number"
        label="survive"
        required
      />

So I thought of creating an array containing all Form.Input id and map them like this:

return (
        myArray.map((element) => {
           <Form.Input id={element} label={element} type="number"/>
        })

How can I group every four elements together with the array.map() function? Manually it would work like this but I'm sure there's a more efficient way as do it manually like this

<Form.Group>
    <Form.Input id="1"/>
    <Form.Input id="2"/>
    <Form.Input id="3"/>
    <Form.Input id="4"/>
</Form.Group>

You cannot do that with just .map(..) because .map(..) returns an array that has the same number of elements as the original array and the expected result is an array that has myArray.length / 4 number of elements.

To achieve this, you can use a combination of .reduce(..) and .map(..) , here is an example:

myArray.reduce((a, c, i) => {
  if (i % 4 === 0) {
    a.push([]);
  }
  a[a.length - 1].push(c);
  return a;
}, []).map((arr) => (
  <Form.Group>
    {arr.map(element => (<Form.Input id={element} label={element} type="number"/>))}
  </Form.Group>
))

What this does is to first create a 2 dimensional array (the inner arrays have 4 elements) and then map both the first and second dimension.

you could do this

return <Form.Group>
{
    myArray.map((element , index) => {
           return <Form.Input key={index} id={element} label={element} type="number"/>
    }
}
</Form.Group>

You could map over chunk of array.

Chunk function taken from here .

const chunk = (arr, size) => Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
arr.slice(i * size, i * size + size)
);

Map over chunks of 4 and form groups

chunk(myArray).map(ch=>{
    //Return a group
    <Form.Group>
    {ch.map(element=>{
        //return element
    })}
    </Form.Group>
}

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