Reputation: 33
I made a <View>
object in react native containing, in a row, multiple <View>
objects that contain text objects.
When the text is more than 1 line, the text containers do not expand to fill the parent component and it looks funny.
Screenshot:
This is the style code:
bigContainer: {
flex: 1,
justifyContent: 'center',
// flexDirection: 'row'
},
textContainer: {
flex: 1,
paddingLeft: 0,
paddingRight: 0,
borderRightWidth: 1,
borderRadius: 0,
borderColor: 'rbga(0, 0, 0, 0.1)',
alignItems: 'center',
justifyContent: 'center',
paddingTop: 7,
paddingBottom: 7,
overflow: 'hidden'
},
text: {
fontSize: 18,
textAlign: 'center'
},
Please help, I do not understand why this happens since I have flex: 1
and my research has not helped me. Thanks !!
UPDATE: SOLVED: I forgot that <TouchableOpacity>
, the container that encloses the text container, also behaves like a flexbox
Upvotes: 3
Views: 8552
Reputation: 5770
In React Native flex works a bit differently, as it only accepts a single number. This is because of the Yoga
layout engine facebook uses
flex: 1
does not mean "grow as much as you need to". When you assign a group of child components that property, what you're essentially saying is that each element with the flex: 1
property should take up as much space as each other element. Think of flex: 1
as assigning a ratio. If you have 1 element with no siblings, it will attempt to fill all available space. If you have 4 elements and they are all siblings, and they are all set to flex: 1
then each will take 1/4 (25%) of the available space.
This can be manipulated as well, say you have 4 elements and 3 of them are set to flex: 1
. You can set the 4th to flex: 2
. That 4th element will now use twice as much space as the other components (40% of available space as opposed to 20%). Flex can also be set to a negative number, which means it will shrink to it's min height and width when needed.
This behavior is pretty much identical to how the flex-grow
property works in CSS. If you want to manipulate the initial size of a flex container without respect to it's siblings, you should use the flex-basis
(flexBasis
in react) property. flexBasis: content
will resize the container based on it's content. flexBasis
also accepts a number, if you would like to manually set the initial width of your containers.
Upvotes: 7