Aximem
Aximem

Reputation: 732

React Native default width

This might be a stupid question but I don't understand how components width works.

When I do :

    render() {
        return (
          <View style={{ height: 100, backgroundColor: 'yellow' }}></View>
        )
    }

My yellow view is visible, takes 100 "height" and full width. Why ? I never set a width, why width is not equal to 0 ?

Upvotes: 3

Views: 5309

Answers (4)

SMhd Asadi
SMhd Asadi

Reputation: 420

Both width and height by default have the value of "auto", but there is a different behavior for width and height. If you don't specify height, it will be 0, on the other hand if you don't specify width, it will take all the space of the parent.

This is because of the alignItems style of the parent. In React Native, each component has this style by default:

alignItems: "stretch"

This means that children of this component, should take all the space in the cross axis, which is width of the parent. That's why width and height have different functionality.

Upvotes: 3

Mohammed Siddeeq
Mohammed Siddeeq

Reputation: 818

  1. The height of your view is 100 because you set as such
  2. The width of your view is not zero because you didn't set it to 0, and zero is NOT the default width value
    • the default value of width is 'auto' because you didn't set it to anything else ('auto' basically 100% of the 'remaining' space of the parent unless other styles make it behave otherwise ie: flex).

The Solution!

  • Just set your width to what you want it to be, either explicitly or with flex

Upvotes: 8

DankWeedHacker
DankWeedHacker

Reputation: 1

React Native uses the Yoga layout engine internally, which is based of the CSS Flexbox specification. In CSS, the width and height of a Block Level element (the only type RN supports) is set to auto by default.

When the width of a Block Level element is set to auto, it will expand to the largest possible width it can, without exceeding the width of it's parent element.

You can read the part of the spec that deals with it here, although note that it isn't exactly an easily understandable document.

Upvotes: 0

Nemi Shah
Nemi Shah

Reputation: 876

Well a view basically wraps to the height and width of it's children unless you pass it both a height and a width. But to achieve what you want you could use flex. For example

<View style={{flex: 1, width: 100, backgroundColor: 'yellow' />

Would give it a width of 100 and full height.

More on flex

Upvotes: 0

Related Questions