1

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

2
  • yup @yevGen-gorbunkov sorry for not responding earlier it's been a very busy weekend. Thanks alot for the solution! Commented Jun 15, 2020 at 10:44
  • No worries. You're very welcome. Commented Jun 15, 2020 at 10:45

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.