Search code examples
javascriptreactjsloopslayout

javascript: React - limit number of components (or columns) rendered per row in a loop/map


I know it seems quite easy... But I can't figure out how to get it. So, any suggestion is truly welcome. Thanks.

What I have

I am using React.js. I have an array of elements (let's say 20).

What I want

I want to render 4 elements (for example) per row.

Wha the problem is

I can't figure out how to limit the amount of components/columns per row.

This code render all components in a row... How can I limit it?

populatingLayout() {
    arrayData.map(item => {
        return (
        <div className="FlexRow">
            <div className="FlexColumn">
                <Component dataProp={item} />
            </div>
        </div>
        )
    }
}

render() {
     return (
         <div className="FlexGrid">
             {this.populatingLayout()}
         </div>
    )
}

Thanks in advance!


Solution

  • I think you're looking for something like this. Let's just say your elements are 20 div elements in a array. Then you could display each four element in a separate row like this.

    class Hello extends React.Component {
    
    constructor(props) {
         super(props);
       }
       
      
    //this function will return array of element 20 divs in this case 
    multipleElements() {
    
       let elements = [];
       for(let i = 0; i < 20; i++) {
                elements.push(
                      <div key={i}> element{i+1} </div>
               )
       }
        return elements;
    }
    
    //this function will separate each four element to display 
    separateElement () { 
     var separateElements = [];
     var multiElements = this.multipleElements();
    
    for(var i = 0; i < multiElements.length; i+=4) {
         var oneRow = [];
         oneRow.push(multiElements.slice(i, i+4).map(item => {
       return <div style={{display: 'inline-block'}}>{item}</div>
    }))
    separateElements.push(oneRow.map(itm => {return <div>{itm}</div>}))
    }
    return separateElements;
    }
                
              
                
    render() {
       return (<div> {this.separateElement()} </div>);
     }
    };
    
    ReactDOM.render(
     <Hello/>,
     document.getElementById('container')
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
    
    <div id="container">
        <!-- This element's contents will be replaced with your component. -->
    </div>