I'm stuck with something it's easier to explain with this sample code
import React from "react";
import { StyleSheet, View } from "react-native";
function App() {
return (
<View style={styles.container}>
<View style={styles.row}>
<View style={styles.square} />
<View style={styles.square} />
<View style={styles.square} />
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "white"
},
row: {
height: 100,
flexDirection: "row",
backgroundColor: "red",
},
square: {
aspectRatio: 1,
margin: 20,
backgroundColor: "green",
}
});
export default App;
At the moment I'm simply drawing 3 green squares inside a red row with a fixed height of 100.
On every device I'll probably have these 3 squares followed by some "free space" on the right. (picture 1)
If the row height is increased, the "free space" on the right is reduced, up to the point the squares exceeds the available width. (picture 2)
Now, I can't have these 3 squares to automatically fit the page, leaving the "free space" only on their bottom when the row height is big enough. (picture 3 and 4)
I could play around onLayout prop or I could do some kind of math on element sizes, but I'd like to keep it simple and try to understand if the issue can be solved using flexbox the correct way.
A couple of pictures to better explain the scenario:
Above how it works right know. picture 1 is ok. Picture 2 is something I don't want. When the row height is not enough to contain the squares, it should act like the pictures below.
Fiddle here
You only need to add align-items: baseline style to the container, and make the .square items to flex-grow: 1 like this
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "white"
},
row: {
flexDirection: "row",
height: 500,
alignItems: 'baseline',
backgroundColor: "red"
},
square: {
aspectRatio: 1,
flexGrow: 1,
backgroundColor: "green",
margin: 20
}
});
the align-items arrange the flex items with their default width, and the flex-grow property will make the items grow to fill the width of the container, and since the flex grow is equal the items growth will be equal across the containers
if you want the .square items to be in the center, you only need to change the align-items property