Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Horizontally Center React Native Flexbox Text that Wraps across Multiple Lines

In React Native, using flexbox, text in my <Text> components are centered Horizontally (and vertically).

This works as expected -- if line of text is short enough that it does not need to wrap onto the next line.

But, when given a long text string, that wraps across multiple lines, the rendered text does not center horizontally !
Instead the wrapped text is aligned to the left edge.

How can I force wrapped lines of text to center horizontally ?

This horizontally centers shortText, but not longText:

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';

class Deck extends React.Component {

  render() {
    const shortText = 'Centered!';  
    const shortText = 'This very long line of text does NOT Center. Instead the wrapped text is aligned to the left edge of the container.';         

    return (
      <View style={styles.container}>
        <View>
          <Text style={styles.titleText}> {shortText} </Text>
          <Text style={styles.titleText}> {longText}  </Text>
        </View>   
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  titleText: {
    fontSize: 27,
    flexWrap: 'wrap', 
    alignSelf: 'center',
  },
});    

Note: I find plenty of Stack Overflow questions/answers, and blog posts
for Vertical centering, and Horizontal centering when the text does Not wrap onto multiple "lines".
But I have been unable to find any for centering horizontal text that wraps to multiple lines.

Also: note that React Native implements "limited style inheritance" for text which differs slightly from the css standard. For example, <Text>inherits color and 'fontSizeproperties only from parentTextcomponents, but notView` components.
Also, the Flexbox layout implementation for React Native differs slightly from the CSS standard.
I don't know if React Native differences affect horizontally centered wrapped text as well, or not.

like image 624
SherylHohman Avatar asked Jan 29 '23 06:01

SherylHohman


1 Answers

You can set the textAlign property like this:

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

You can see the docs for the textAlign property here: https://reactnative.dev/docs/text-style-props#textalign

like image 151
Orlandster Avatar answered Jan 30 '23 19:01

Orlandster