'Child Elements with same width in horizontal ScrollView with FlexBox
Target platform: IOS
I have a ScrollView within a SafeAreaView. Within the ScrollView I have x child elements (TouchableOpacity if that matters). These child elements also have exactly 1 children (a Text element).
The Goal is to align the TouchableOpacities horizontally within the ScrollView. And if I have a lot of TouchableOpacities, the View should be horizontaly scrollable.
I have accomplished everything mentioned so far and can be seen here: Snack
Now I want all the TouchableOpacities to have the same width. I have found the property contentContainerStyle and thought i could use flexGrow: 1... but that does absolutely nothing.
Is what i want even possible? I dont want to set a minWidth or a fixed with.
What am I missing here? Thanks in advance!
export default function App() {
return (
<SafeAreaView style={styles.safeAreaView}>
<ScrollView style={styles.scrollView} contentContainerStyle={styles.contentContainer} horizontal={true}>
<TouchableOpacity style={styles.touchableOpacity}>
<Text style={styles.text}>short</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.touchableOpacity}>
<Text style={styles.text}>slightly more</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.touchableOpacity}>
<Text style={styles.text}>short</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.touchableOpacity}>
<Text style={styles.text}>a lot of text within the button</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.touchableOpacity}>
<Text style={styles.text}>short again</Text>
</TouchableOpacity>
</ScrollView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safeAreaView: {
backgroundColor: "black",
height: 100,
},
scrollView: {
},
contentContainer: {
backgroundColor: "white",
},
touchableOpacity: {
backgroundColor: "green",
marginHorizontal: 10,
marginVertical: 10,
},
text: {
fontSize: 18,
marginHorizontal: 10,
},
});
Edit:
In React native, flexbox works differently!
The following solution works on the web, but not on an ios-device (we are using react-native with expo!)
contentContainer: {
flexGrow: 1, // add this
backgroundColor: "white",
},
touchableOpacity: {
flex: 1, // add this
backgroundColor: "green",
},
What else is missing for it to work on IOS?
Solution 1:[1]
Given Flex to each TouchableOpacity and FlexGrow to Scrollview you will get what you want. Try these styles.
To explain, we say that you can expand the scrollview by giving FlexGrow. We say share equal space by giving Flex to each element.
const styles = StyleSheet.create({
safeAreaView: {
backgroundColor: "black",
height: 100,
},
contentContainer: {
flexGrow: 1, // add this
backgroundColor: "white",
},
touchableOpacity: {
flex: 1, // add this
backgroundColor: "green",
},
text: {
fontSize: 18,
},
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HyopeR |
