Ľubomír
Ľubomír

Reputation: 1161

React.js+Bootstrap rendering rows

I am using bootstrap and I want to render 4 columns in row. However I do not know how many columns I will have, so it should work for any number of columns and also first column can be different react component then other columns.

What I want to achieve:

<div class="row">
  <div class="col-md-3 component-type-1">...</div>
  <div class="col-md-3 component-type-2">...</div>
  <div class="col-md-3 component-type-2">...</div>
  <div class="col-md-3 component-type-2">...</div>
</div>
<div class="row">
  <div class="col-md-3 component-type-2">...</div>
  <div class="col-md-3 component-type-2">...</div>
  <div class="col-md-3 component-type-2">...</div>
  <div class="col-md-3 component-type-2">...</div>
</div>

I tried something but did not managed to achieve what I want..

    import chunk from 'lodash/chunk.js'

    class Test extends React.Component {

    render() {

           let component1=null;
            if (this.state.shouldBeComponent1) {
                component1=<Component1 key="component1" />;
            }

            let items = [];
            if (component1!=null) items.push(component1);

            this.state.dataForComponents2.forEach((data) => {
                items.push(<Component2 key={data.ID} />)
            });

            const rows = chunk(items, 4);

            let pageBody=null;
            if (items.length>0) {
                pageBody=(
                          rows.map((row) => {
                                <div className="row">
                                    {
                                        row.map((item) => (
                                            {item}
                                        ))
                                    }
                                </div>})

                        );
            }

            return (
                <div>
                    <div className="header">
                         ///Other unreleated code
                    </div>
                        {pageBody}

                </div>
        );
  }

Upvotes: 1

Views: 1500

Answers (1)

fumihwh
fumihwh

Reputation: 1249

Seems something wrong with your pageBody

Try this.

    let pageBody= [];
    if (items.length>0) {
      rows.forEach((row, idx) => {
        pageBody.push 
        (
          <div key={idx} className="row">
          {row}
          </div>
        )}
      );                 
    } 

And example here

Upvotes: 2

Related Questions