Home > Mobile >  Setting backgroundColor of view in react native covers another element
Setting backgroundColor of view in react native covers another element

Time:09-23

I have a page in my react native app that renders a custom <Header> component at the top, followed by a View (let's call it BottomView) wrapped in a Pressable. The last component rendered as part of the Header is also a View, namely a thin "line" with a blue-ish color (let's call it TopView). Here is a picture to make it more clear:

Structure

Now, in the picture shown above, BottomView has no backgroundColor set and the TopView has its defined height. So far so good.

However, if I try to set a backgroundColour to BottomView (red used here for emphasis), a part of TopView actually gets covered by BottomView as shown below:

TopView getting hidden

You can clearly see that TopView has about half its original height. Do note that there are no margins, paddings, etc. on any of the elements, and the only thing changing is the backgroundColor of BottomView.

That is to say, setting backgroundColor on BottomView somehow "pushes" the View upward.

For reference, here are the styles of the components mentioned:

TopView: { borderRadius: 80, borderWidth: 0.5, borderColor: 'transparent', width: '100%', height: '5%', alignSelf: 'center' }

BottomView: { flex: 1, alignItems: 'center', justifyContent: 'center' }

Header View (which wraps TopView): { width: '100%', height: '20%', alignItems: 'center', justifyContent: 'center' }

(Pressable that wraps BottomView has no style applied)

I am at a loss as to how or why this is happening, any help or direction would be greatly appreciated.

EDIT: Here is a minimal example that showcases the problem. You just need to uncomment the backgroundColor directive at the bottom of App.js

P.S. I am using "react": "16.13.1" and "react-native": "0.63.2".

CodePudding user response:

In your Header.js, you have 2 views inside a view. For the first view you have height:100% and for the second view(that seperator) you have 5%.

I can't explain it with getting too technical but it looks like an overflow issue.

I just changed the heights to 95% and 5% it works fine.

But if I were you, I would make the first view flex:1 and I would give a constant height for the seperator like 5 pixels.

CodePudding user response:

@SickRanchez's solution is right and I am accepting it as the correct one, because indeed, that aggregate 105% height seems to be causing the issue.

However, for an alternate solution I found, adding zIndex: -1 to BottomView also fixes the problem, as it makes TopView render on top of BottomView (ref).

  • Related