Reputation: 45
I'm working on a react native app , i want to dynamically fill my grid layout with inputs from server , i want the result to be in that shape :
<Grid>
<Row>
<Col
style={{ backgroundColor: colors.dark_orange, height: h(30) }}
>
</Col>
<Col
style={{ backgroundColor: colors.green, height: h(30) }}
></Col>
<Col
style={{ backgroundColor: colors.gris, height: h(30) }}
></Col>
</Row>
<Row>
<Col
style={{ backgroundColor: colors.orange, height: h(30) }}
></Col>
<Col
style={{ backgroundColor: colors.purple, height: h(30) }}
></Col>
<Col style={{ backgroundColor: colors.red, height: h(30) }}></Col>
</Row>
<Row>
<Col
style={{ backgroundColor: colors.transparent, height: h(30) }}
></Col>
<Col
style={{ backgroundColor: colors.white, height: h(30) }}
></Col>
<Col
style={{ backgroundColor: colors.green, height: h(30) }}
></Col>
</Row>
<Row>
<Col
style={{ backgroundColor: colors.dark_orange, height: h(30) }}
></Col>
<Col
style={{ backgroundColor: colors.green, height: h(30) }}
></Col>
<Col
style={{ backgroundColor: colors.gris, height: h(30) }}
></Col>
</Row>
<Row>
<Col
style={{ backgroundColor: colors.transparent, height: h(30) }}
></Col>
<Col
style={{ backgroundColor: colors.white, height: h(30) }}
></Col>
<Col
style={{ backgroundColor: colors.green, height: h(30) }}
></Col>
</Row>
</Grid>
</ScrollView>
</View>
As you can see i hardcoded the inputs and the shape of the grid (each row has 3 columns), i want to make a function that take all the inputs from the server and render something like what i hardcoded .
Upvotes: 1
Views: 762
Reputation: 15705
First, you'd need to get the shape of your data to reflect the grid:
// Outer array represents rows, inner array represents columns
const grid = [
[
{ backgroundColor: colors.dark_orange, height: h(30) },
...
], [
...
]
]
Then, just use something like .map
to iterate over your data and return the relevant JSX:
const renderRow = (row) => {
return <Row>{row.map(renderCol)}</Row>;
}
const renderCol = (col) => {
const { backgroundColor, height } = col;
return <Col style={{ backgroundColor, height }}></Col>;
};
<Grid>{grid.map(renderRow)}</Grid>
Upvotes: 1