Search code examples
cssreact-nativeflexbox

Align icon to left and text to center in react native


I am trying to use flexbox to align my icon to the left of a button view and the text to the center. Currently they are both aligned to the center but I am not sure how to get my icon on the very left edge of the button while keeping the text centered in the view

Right now my button looks like this:

enter image description here

I am using https://github.com/APSL/react-native-button for buttons and https://github.com/oblador/react-native-vector-icons for icons

Below is some of my code:

    <Button style={signupStyles.facebookButton}>
      <View style={signupStyles.nestedButtonView}>
        <Icon
          name="facebook"
          size={30}
          color={'white'}

        />
        <Text style={signupStyles.buttonText}>Continue with Facebook</Text>
      </View>
    </Button>

    var signupStyles = StyleSheet.create({
    buttonText: {
      color: 'white',
      fontWeight: 'bold',
      textAlign: 'center',
    },

    facebookButton: {
      backgroundColor: styleConstants.facebookColor,
      borderColor: styleConstants.facebookColor,
      borderWidth: 2,
      borderRadius: 22,
    },

    nestedButtonView: {
     flexDirection: 'row',
     alignItems: 'center',
    },

  });

Solution

  • That you can do by setting icon to a width and give text padding-right, text-align and flex:1

    <Button style={signupStyles.facebookButton}>
      <View style={signupStyles.nestedButtonView}>
        <Icon
          name="facebook"
          size={30}
          color={'white'}
        />
        <Text style={signupStyles.buttonText}>Continue with Facebook</Text>
      </View>
    </Button>
    
    var signupStyles = StyleSheet.create({
      buttonText: {
        color: 'white',
        fontWeight: 'bold',
        textAlign: 'center',
      },
    
      facebookButton: {
        backgroundColor: styleConstants.facebookColor,
        borderColor: styleConstants.facebookColor,
        borderWidth: 2,
        borderRadius: 22,
      },
    
      nestedButtonView: {
        flexDirection: 'row',
        alignItems: 'center',
      },
    
      iconLeft: {
        width: '40px',  
      },
    
      buttonText: {
        flex: 1,
        paddingRight: '40px',
        textAlign: 'center',
      },
    
    });