Skip to content

How to start a component in a loop and close it all 3 iterations

Hello i search solution for open tag in loop and close it all the 3 iteration. The goal is to create a grill based on container row and col. My problem is I do not know how to do.

Exemple :

        const arrayName = ["john", "bob", "joe", "mat", "toto", "tata"]
        let arrayEl = [];
        let count = 1; 
          for ( let i = 0; i < arrayName.length; i++ ) {
             let name = arrayName[i]

             if (count === 1) {
                 arrayEl.push(<div className="row">);
                 arrayEl.push(<p className="col">{name}</p>);
                 count ++;
             if (count === 3) {
                 arrayEl.push(<p className="col" >{name}</p>);
                 count = 1;
        return (<div className="container">{arrayEl}</div>)

and the result wanted is :

<div className="container">
    <div className="row">
        <div className="col">john</div>
        <div className="col">bob</div>
        <div className="col">joe</div>
    <div className="row">
        <div className="col">mat</div>
        <div className="col">toto</div>
        <div className="col">tata</div>

thank you for some help


The problem is we can’t add someone element or componant without close it.

is Bad :

arrayEl.push(<div className="row">)

is good :

arrayEl.push(<div className="row"/>) or arrayEl.push(<div className="row"></div>)



I would change your data from:

 ["john", "bob", "joe", "mat", "toto", "tata"]
// to
 [["john", "bob", "joe"], ["mat", "toto", "tata"]]

Checkout for example of that

And then you can nest 2 .map to replicate the structure in JSX:

const chunk = (arr, chunckSize) => arr.reduce((chunks, value, index) => {
  const chunckIndex = Math.floor(index / chunckSize)
  const c = chunks[chunckIndex] || (chunks[chunckIndex] = [])
  return chunks
}, [])

render() {
    const arrayName = ["john", "bob", "joe", "mat", "toto", "tata"]

    return (
        <div className="container">
            {chunk(arrayName, 3).map(names => (
                <div className="row">
                    { => <div className="col">{name}</div>)}
User contributions licensed under: CC BY-SA
5 People found this is helpful