React-native: margin not taken into account in a flex layout

Viewed 5046

I encountered a few times issues with margins when layouting views using flexbox.

I managed to reproduce the issue with a small code snippet:

Here is a custom component:

class MyView extends Component {
  render() {
    return (
      <View style={
        {
          backgroundColor: 'green',
          width: 50,
          height: 50
        }
      }/>
    );
  }
}

and here is how I use it:

<View style={{ flexDirection: 'column' }}>
  <MyView />
  <MyView style={{ marginTop: 12 }}/>
</View>

So I am expecting to see 2 green squares on top of each other, separated by 12px (due to the marginTop). Instead here is what I see:

nomargin

The two squares touch each other. I have no idea why the margin is not taken into account.

I tried debugging the bottom view with the inspector tool, here is what's getting displayed:

nomargin-debug

You can actually see the margin on this image (light orange). Any idea why the margin is not taken into account?

2 Answers

I faced the same issue when using flex and I used

justifyContent = "space-between"

margin top and marginBottom didn't work for me .Later when I removed the justifyContent and just put

alignItems: "center", flexDirection: "column"

instead margin top and bottom worked for me .

Related