sheldon.cooper
sheldon.cooper

Reputation: 217

Center an image in a React Native component

I have started playing with React Native and I'm trying to create a simple image button component just to get used to the language. Here is what I have:

'use strict';

const React = require('React');
const PropTypes = require('prop-types');

import {
    Platform, TouchableOpacity,
    StyleSheet, Dimensions,
    Text, Image,
    View
  } from 'react-native';
const TouchableNativeFeedback = require('TouchableNativeFeedback');


const MyBrown = '#89664C';
const styles = StyleSheet.create({
    button: Platform.select({
        ios: {
        },
        android: {
            elevation: 4,
            backgroundColor: MyBrown,
            borderRadius: 2
        }
    }),
    text: Platform.select({
        ios: {
            color: 'white',
            textAlign: 'center',
            padding: 8,
            fontSize: 18
        },
        android: {
            color: 'white',
            textAlign: 'center',
            padding: 8,
            fontWeight: '500',
        }
    }),
    icon: {
        width: 60,
        height: 60,
    }
});

export default class MyButton extends React.Component{

    render(){            
        return(
            <View style={styles.button}>
                <TouchableOpacity>                    
                    <Image source={this.props.src} style={styles.icon} />
                    <Text style={styles.text}>{this.props.text}</Text>
                </TouchableOpacity>
            </View>
            )
    }
}

This renders as I'd expect when I run the app, but the image is left aligned whilst the text is centered. Now I thought I could use Flexbox and add {flex:1} to the parent View or TouchOpacity elements, but as soon as I do this the control no longer renders in my app.

Two questions on this:

  1. What is the recommended way of centering the image in React Native?
  2. Why, when I add the flex:1 to ether of the parent controls does it no longer render at all?

Thank you

Upvotes: 6

Views: 14916

Answers (1)

Wojtek Szafraniec
Wojtek Szafraniec

Reputation: 599

Basically the best way to center image is to wrap it with parent view and add flex styles to it and there is no need to pass flex: 1

> justifyContent: 'center',
> alignItems: 'center',
  1. Prefered way to take care of image size is width and height, flex: 1 you should use for background images etc

Upvotes: 7

Related Questions