George B
George B

Reputation: 2712

Center an item, then have an item to the left - Flexbox React Native

Using flexbox in React Native I'm having a lot of trouble trying to do the following seemingly simple task:

I have two item inside a container. I want one centered, and the other one to lie directly to the left of it.

Upvotes: 3

Views: 3887

Answers (1)

Nader Dabit
Nader Dabit

Reputation: 53711

You can change the flex size properties of the two outer components, and as long as they are the same, the middle item will be centered.

Notice the justifyContent:'flex-end' property of the first component. This styling is what is making the item lie directly to the left of the middle item.

  <View style={styles.container}>
    <View style={styles.component1}>
        <Text>Right</Text>
    </View>
    <View style={styles.component2}>
        <Text style={{ textAlign:'center' }}>I am the Center Component</Text>  
    </View>
    <View style={styles.component3}></View>
  </View>

  container: {
    flexDirection:'row',
    flex:1,
    marginTop:60
  },
  component1: {
    flex:1,
    flexDirection: 'row',
    justifyContent: 'flex-end',
    height:80
  },
  component2: {
    flex:1,
    height:80,
    backgroundColor: 'red',
    justifyContent:'center'
  },
  component3: {
    flex:1,
  }

Also, the entire code is below:

'use strict';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
} = React;

var SampleApp = React.createClass({
  render: function() {
    return (
      <View style={styles.container}>
        <View style={styles.component1}>
                    <Text>Right</Text>
        </View>
        <View style={styles.component2}>
            <Text style={{ textAlign:'center' }}>I am the Center Component</Text>  
        </View>
        <View style={styles.component3}></View>
      </View>
    );
  }
});

var styles = StyleSheet.create({
  container: {
    flexDirection:'row',
    flex:1,
    marginTop:60
  },
  component1: {
    flex:1,
    flexDirection: 'row',
    justifyContent: 'flex-end',
    height:80
  },
  component2: {
    flex:1,
    height:80,
    backgroundColor: 'red',
    justifyContent:'center'
  },
  component3: {
    flex:1,
  }
});

AppRegistry.registerComponent('SampleApp', () => SampleApp);

Upvotes: 7

Related Questions