I'm trying to do a two column layout in React Native from a list of items. It only seems to work if I define the width of the items, I would like to define just a percentage of the parent width (0.5 would make a 2 column layout, but 0.25 would make a 4 column one). Can this be done?
export default class App extends Component {
render() {
return (
<View style={[styles.container, {width:width}]}>
<View style={styles.item}><Text>{'item1'}</Text></View>
<View style={styles.item}><Text>{'item2'}</Text></View>
<View style={styles.item}><Text>{'item3'}</Text></View>
<View style={styles.item}><Text>{'item4'}</Text></View>
<View style={styles.item}><Text>{'item4'}</Text></View>
<View style={styles.item}><Text>{'item5'}</Text></View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
},
item :{
flex: 0.5, //why this doesnt work???
// width: 150, //using fixed item width instead of flex: 0.5 works
height: 100,
padding: 10,
backgroundColor: 'red',
// flexGrow: 1,
// flexShrink: 0,
}
});
You can play with it here: https://snack.expo.io/SyBjQuRxm
Css working equivalent: https://codepen.io/klamping/pen/WvvgBX?editors=110
Obviously I could do something like creating a container for each column, but that's not the point:
render() {
return (
<View style={[styles.container, {width:width}]}>
<View style={styles.column1}>
<View style={styles.item}><Text>{'item1'}</Text></View>
<View style={styles.item}><Text>{'item2'}</Text></View>
<View style={styles.item}><Text>{'item3'}</Text></View>
</View>
<View style={styles.column2}>
<View style={styles.item}><Text>{'item4'}</Text></View>
<View style={styles.item}><Text>{'item4'}</Text></View>
<View style={styles.item}><Text>{'item5'}</Text></View>
</View>
</View>
);
}
It is possible if you use percentage values for the widths:
<View style={styles.container}>
<View style={styles.item}>
...
</View>
</View>
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
alignItems: 'flex-start' // if you want to fill rows left to right
},
item: {
width: '50%' // is 50% of container width
}
})