Search code examples
javascriptreactjsreact-nativejsxreact-native-text

Nested Text, Vertical Align not working - React Native


Ok, Let's make this simple. I've two Text components, one inside another. The first Text has fontSize of 60, and the nested one has fontSize of 20. As the font size varies, the nested Text sits base aligned. I want the nested Text vertically center aligned with the parent one.

Code

// @flow
import React, { Component } from 'react';
import { Text } from 'react-native';

type PropTypes = {}
export default class SampleVC extends Component<PropTypes> {
    render() {
        return (
            <Text style={{ fontSize: 60 }}>
                Big Text
                <Text style={{ fontSize: 20 }}>Small Text</Text>
            </Text>
        );
    }
}

Current Output

Current Ouput

Needed Output

enter image description here

I know this is a simple scenario, but as am new to react native , i can't figure it out. I've searched all over the web,but couldn't find any helpful resource.


Solution

  • It's not possible to achieve what you're trying using just nested Text.

    The Only option, use a View to wrap your texts like,

    <View style={{ flexDirection: 'row', alignItems: 'center' }} >
      <Text style={{ fontSize: 60 }}>Big Text</Text>
      <Text style={{ fontSize: 20 }}>Small Text</Text>
    </View>
    

    And if you want to use it often, create your own custom component for the above like,

    function CustomNextedText (props) {
      return (
        <View style={{ flexDirection: 'row', alignItems: 'center' }} >
          <Text style={{ fontSize: 60 }}>{props.bigText}</Text>
          <Text style={{ fontSize: 20 }}>{props.smallText}</Text>
        </View>
      );
    }
    

    Use it anywhere like any other react-native component,

     <CustomNextedText bigText='Big Text' smallText='Small Text'/>
    

    Hope it helps.