Rishav Sinha
Rishav Sinha

Reputation: 359

Render 2 columns using map in react

Hi i have a data array like the following

let array = ['first','second','third','fourth','fifth','sixth']

Now i am looking to loop over this using map, and render 2 columns which starts as soon as there is more than four item in the array.For the above case i want to have the following layout.

column1 | column 2
-------- ----------
first   | fifth
second  | sixth
third   |
fourth  |

what i did is using a table ,but i don't want to use a table for this.I want to create a simple component for this.

How would i achieve this using map rendering in react.

Upvotes: 0

Views: 2145

Answers (1)

Chamsddine Bouzaine
Chamsddine Bouzaine

Reputation: 1579

this is how you build the table using only divs

function splitArray(array, n) {
  let [...arr] = array;
  let res = [];
  while (arr.length) {
    res.push(arr.splice(0, n));
  }
  return res;
}

const rowsPerCol = 4
const array = ['first','second','third','fourth','fifth','sixth']
const columns = splitArray(array, rowsPerCol)

const Column = props => (
<div className="column">
  <Row label="label" rows={props.rows}/>
  </div>
);

const Row = ({rows}) => (
rows.map((data,key) => <div key={key}>{data}</div>)
);

// Example class component
class Table extends React.Component {
  render() {
    return (
      <div className="table">
        {columns.map((rows,key) => <Column key={key} rows={rows} />)}
      </div>
    );
  }
}

// Render it
ReactDOM.render(
  <Table />,
  document.getElementById("react")
);
.column {
padding : 5px;
border : 2px dashed black;
}

.table {

display : flex;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Upvotes: 3

Related Questions