Ad

React Native Flexbox - How To Do Percentages || Columns || Responsive || Grid Etc

After working with react native on iOS for the last couple of weeks, I seem to have come across some shortcomings of flex styling... Particularly when it comes to "responsive" behavior.

For instance, lets say you want to create a view that contains cards (the metadata for these cards comes from an API). You want the cards to be 50% of the view width minus the margin & padding, and to wrap after each 2.

enter image description here

The current implementation I have for this view splits the returned array into rows with 2 items. The list container has flex: 1, flexDirection: 'column, the rows have flex: 1 and then each card has flex: 1. The end result is each row has 2 columns which evenly take up half the view width.

It seems like there is no trivial way to do this in React Native styles, without using javascript to do some sort of pre-processing on the data so that it comes out styled correctly. Does anyone have any suggestions?

Ad

Answer

React Native already has percentage support:

<View style={[style.parent]}>
    <View style={[style.child, {backgroundColor: '#996666'} ]} />
    <View style={[style.child, {backgroundColor: '#339966'} ]} />
    <View style={[style.child, {backgroundColor: '#996633'} ]} />
    <View style={[style.child, {backgroundColor: '#669933'} ]} />
</View>

var style = StyleSheet.create({
    parent: {
        width: '100%', 
        flexDirection: 'row', 
        flexWrap: 'wrap'
    },
    child: {
        width: '48%', 
        margin: '1%', 
        aspectRatio: 1,
    }
})

enter image description here

Ad
source: stackoverflow.com
Ad