Shury
Shury

Reputation: 578

Render array as a matrix (n items per row)

I have a view and inside it a map function:

<View style={{width: 500, height: 500}}>
      {[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15].map((x,i) => {
            return(
                   <View style={{width: 50, height: 50, backgroundColor: 'red'}}></View>
            )
      })} 
</View>

How can I map this into a pattern? Like 5 on a row?

enter image description here

Upvotes: 1

Views: 745

Answers (2)

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15540

You may split your source array into chunks (rows) of desired length and use nested .map() loops to render rows and cells within them:

const chunkArr = (arr, size) => 
   arr.reduceRight((r,i,_,s) => (r.push(s.splice(0,size)),r),[])

Following is a complete live-demo of that concept:

const { useState } = React,
      { render } = ReactDOM,
      rootNode = document.getElementById('root')
      
const cellData = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]      
      
const Matrix = ({cells}) => {
  const rows = cells.reduceRight((r,i,_,s) => (r.push(s.splice(0,5)),r),[])
  return (
    <div className="wrapper">
      {
        rows.map((row,i) => (
          <div key={i} className="row">
            {
              row.map((cell,j) => (
                <div key={j}  className="cell">
                  {cell}
                </div>
              ))
            }
          </div>
        ))
      }
    </div>
  )
}

render (
  <Matrix cells={cellData} />,
  rootNode
)
.wrapper {
  display: flex;
  flex-direction: column;
}

.row {
  display: flex;
  flex-direction: row;
}

.cell {
  width: 20px;
  height: 20px;
  margin: 5px;
  background-color: red;
  color: #fff;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script><div id="root"></div>

Upvotes: 1

Arun Ravilla
Arun Ravilla

Reputation: 93

You can achieve this using flexbox and flexWrap, see the below given example <View style={{display: "flex"; flexDirection: "row", flexWrap: "wrap", flex: 1;}}> </View>

You can read this documentation to achieve this https://reactnative.dev/docs/flexbox

Upvotes: 2

Related Questions