Warm tip: This article is reproduced from stackoverflow.com, please click
android react-native react-native-android reactjs

Text position center React Native

发布于 2020-03-27 10:15:09

App screenshot. Title bar says "Albums!", rest of app is blank I have the following header component for my app:

const Header = () => {
const { textStyle, viewStyle } = styles;

return (
    <View style={viewStyle}>
        <Text style={textStyle}>Albums!</Text>        
    </View>
 );
};

And styles for this component are as follows:

const styles = {
viewStyle: {
    backgroundColor: '#F8F8F8',        
    justifyContent: 'center', //Y-axis
    alighItems: 'center', // x-axis 
    height: 60,
    paddingTop: 15,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.8,
    elevation: 2,
    position: 'relative'
},
textStyle: {
    fontSize: 20
 }
};

I'm learning react native from Udemy. With this code the tutor positions the text in the center of the container [Red color box]. But it doesn't work in my emulator.

Does react styles render differently in ios and android ? As the tutor was running/writing codes in mac.

Questioner
Pawan Rai
Viewed
171
Tim 2019-07-03 20:15

On android devices you need to add textAlign: 'center' to your Text Component style as well:

textStyle: {
    fontSize: 20,
    textAlign: 'center',
}

Output:

output

Example:

https://snack.expo.io/@tim1717/tactless-chocolates