I am new to React Native so this might be a silly question.
What I am trying to get is something like this :
Where I have a parent view with 2 children, Image and Text, aligned vertically to the left. What I want is the parent view to cover only the width of its children. But instead what I get is this :
The parent view stretches to the complete width of the mobile screen.
Here is my code :
render () (<View style={{backgroundColor: '#333333'}}>
<Image source={btnImageSource} />
<Text>Some label</Text>
</View>);
Something similar to Android's 'wrap-content' width value.
Views wrap their content by default if 'flex' attribute is not set. If you need the view to fill parent width or height set 'alignSelf' attribute to "stretch". When flex is not set, the view does not wrap all of its children, it shrinks and children become overlapped so that the entire layout is not visible.
To get the parent height and width in React: Set the ref prop on the element. In the useEffect hook, update the state variables for the height and width. Use the offsetHeight and offsetWidth properties to get the height and width of the element.
You will be able to do this using flex
. I found this guide to be very helpful when working with flex.
A good starting point would be to create a parent View that is flexDirection: row, justifyContent: flex-start
render () (
<View style={{justifyContent: 'flex-start', flexDirection: 'row'}}>
<View style={{backgroundColor: '#333333'}}>
<Image source={btnImageSource} />
<Text>Some label</Text>
</View>
</View>
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With