Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make parent's width wrap its content in React Native?

I am new to React Native so this might be a silly question.

What I am trying to get is something like this : enter image description here

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 :

enter image description here

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.

like image 752
Aditya Avatar asked Dec 23 '17 09:12

Aditya


People also ask

How do you wrap content within view React Native?

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.

How do you find the parent width in React Native?

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.


1 Answers

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>
);
like image 173
Corey Avatar answered Sep 21 '22 21:09

Corey