MartinMoizard
MartinMoizard

Reputation: 6680

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

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?

Upvotes: 3

Views: 5948

Answers (2)

Payel Dutta
Payel Dutta

Reputation: 800

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 .

Upvotes: 2

Dan
Dan

Reputation: 8844

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

MyView.propTypes = {
  style: React.propTypes.shape({
    marginTop: React.propTypes.number
  })
}

MyView.defaultProps = {
  style: {
    marginTop: 0
  } 
}

You are passing style into MyView as a prop. I've added propTypes and defaultProps as you only pass the style prop on occasion.

From the React docs

All of the core components accept a prop named style.

Because your component is not a core component, style doesn't work as you expect it to.

Upvotes: 1

Related Questions