[reactjs] ReactNative: how to center text?

How to center Text in ReactNative both in horizontal and vertical?

I have an example application in rnplay.org where justifyContent="center" and alignItems="center" is not working: https://rnplay.org/apps/AoxNKQ

The text should being centered. And why is there a margin at the top between the text (yellow) and parent container?

Code:

'use strict';

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

var SampleApp = React.createClass({
  render: function() {
    return (
            <View style={styles.container}>
                <View style={styles.topBox}>
                    <Text style={styles.headline}>lorem ipsum{'\n'}ipsum lorem lorem</Text>

                </View>
                <View style={styles.otherContainer}>
                </View>
            </View>
    );
  }
});

var styles = StyleSheet.create({

    container: {
        flex: 1,
        flexDirection: 'column',
        backgroundColor: 'red',
        justifyContent: 'center',
        alignItems: 'center',
    },

    topBox: {
        flex: 1,
        flexDirection: 'row',
        backgroundColor: 'lightgray',
        justifyContent: 'center',
        alignItems: 'center',
    },
    headline: {
        fontWeight: 'bold',
        fontSize: 18,
    marginTop: 0,
        width: 200,
        height: 80,
    backgroundColor: 'yellow',
        justifyContent: 'center',
        alignItems: 'center',
    },

  otherContainer: {
        flex: 4,
        justifyContent: 'center',
        alignItems: 'center',
    backgroundColor: 'green',
    },


});

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

module.exports = SampleApp;

This question is related to reactjs flexbox react-native

The answer is


Already answered but I'd like to add a bit more on the topic and different ways to do it depending on your use case.

You can add adjustsFontSizeToFit={true} (currently undocumented) to Text Component to auto adjust the size inside a parent node.

  <Text adjustsFontSizeToFit={true} numberOfLines={1}>Hiiiz</Text>

You can also add the following in your Text Component:

<Text style={{textAlignVertical: "center",textAlign: "center",}}>Hiiiz</Text>

Or you can add the following into the parent of the Text component:

<View style={{flex:1,justifyContent: "center",alignItems: "center"}}>
     <Text>Hiiiz</Text>
</View>

or both

 <View style={{flex:1,justifyContent: "center",alignItems: "center"}}>
     <Text style={{textAlignVertical: "center",textAlign: "center",}}>Hiiiz</Text>
</View>

or all three

 <View style={{flex:1,justifyContent: "center",alignItems: "center"}}>
     <Text adjustsFontSizeToFit={true} 
           numberOfLines={1} 
           style={{textAlignVertical: "center",textAlign: "center",}}>Hiiiz</Text>
</View>

It all depends on what you're doing. You can also checkout my full blog post on the topic

https://medium.com/@vygaio/how-to-auto-adjust-text-font-size-to-fit-into-a-nodes-width-in-react-native-9f7d1d68305b


Simple add

textAlign: "center"

in your styleSheet, that's it. Hope this would help.

edit: "center"


Wherever you have Text component in your page just you need to set style of the Text component.

 <Text style={{ textAlign: 'center' }}> Text here </Text>

you don't need to add any other styling property, this is spectacular magic it will set you text in center of the your UI.


used

textalign:center

at the view


Set in Parent view

justifyContent:center

and in child view alignSelf:center


const styles = StyleSheet.create({
        navigationView: {
        height: 44,
        width: '100%',
        backgroundColor:'darkgray',
        justifyContent: 'center', 
        alignItems: 'center' 
    },
    titleText: {
        fontSize: 20,
        fontWeight: 'bold',
        color: 'white',
        textAlign: 'center',
    },
})


render() {
    return (
        <View style = { styles.navigationView }>
            <Text style = { styles.titleText } > Title name here </Text>
        </View>
    )

}

Set these styles to image component: { textAlignVertical: "center", textAlign: "center" }


Okey , so its a basic problem , dont worry about this just write the <View> component and wrap it around the <Text> component

<View style={{alignItems: 'center'}}>
<Text> Write your Text Here</Text>
</View>

alignitems:center is a prop use to center items on crossaxis


justifycontent:'center' is a prop use to center items on mainaxis


You can use alignSelf property on Text component

{ alignSelf : "center" }

this is a example for Horizontal and Vertical alignment simultaneously

<View style={{width: 200, flexDirection: 'row',alignItems: 'center'}}>
     <Text style={{width: '100%',textAlign: 'center'}} />
</View>

Horizontal and Vertical center alignment

<View style={{flex: 1, justifyContent: 'center',alignItems: 'center'}}>
     <Text> Example Test </Text>
</View>

textAlignVertical: "center"

is the real magic.


In addition to the use cases mentioned in the other answers:

To center text in the specific use case of a BottomTabNavigator, remember to set showIcon to false (even if you don't have icons in the TabNavigator). Otherwise the text will be pushed toward bottom of Tab.

For example:

const TabNavigator = createBottomTabNavigator({
  Home: HomeScreen,
  Settings: SettingsScreen
}, {
  tabBarOptions: {
    activeTintColor: 'white',
    inactiveTintColor: 'black',
    showIcon: false, //do this
    labelStyle: {
      fontSize: 20,
      textAlign: 'center',
    },
    tabStyle: {
      backgroundColor: 'grey',
      marginTop: 0,
      textAlign: 'center',
      justifyContent: 'center',
      textAlignVertical: "center"
    }
  }

first add in parent view flex:1, justifyContent: 'center', alignItems: 'center'

then in text add textAlign:'center'


The following property can be used: {{alignItems: 'center'}}

<View style={{alignItems: 'center'}}>
 <Text> Hello i'm centered text</Text>
</View>

You can use two approaches for this...

  1. To make text align center horizontally, apply this Property (textAlign:"center"). Now to make the text align vertically, first check direction of flex. If flexDirection is column apply property (justifyContent:"center") and if flexDirection is row is row apply property (alignItems : "center") .

  2. To Make text align center apply same property (textAlign:"center"). Now to make it align vertically make the hieght of the <Text> </Text> equal to view and then apply property (textAlignVertical: "center")...

Most Probably it will Work...


Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to flexbox

Force flex item to span full row width vuetify center items into v-flex Equal height rows in CSS Grid Layout display: flex not working on Internet Explorer Center the content inside a column in Bootstrap 4 Vertical Align Center in Bootstrap 4 How to use zIndex in react-native Bootstrap 4 align navbar items to the right Does 'position: absolute' conflict with Flexbox? Make flex items take content width, not width of parent container

Examples related to react-native

How to resolve the error on 'react-native start' React Native Error: ENOSPC: System limit for number of file watchers reached How to update core-js to core-js@3 dependency? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65 How can I force component to re-render with hooks in React? What is useState() in React? Getting all documents from one collection in Firestore ReactJS: Maximum update depth exceeded error React Native: JAVA_HOME is not set and no 'java' command could be found in your PATH