Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 586
theapache64 Avatar asked May 22 '18 12:05

theapache64


3 Answers

You can wrap nested Text in a View but nested View must have width and height. If you do not have any problem with this constraint, this is a good solution.

<Text style={{ fontSize: 60 }}>
      Big Text
      <View style={{ height:40, width:100, justifyContent: 'center', alignItems: 'center' }}>
            <Text style={{ fontSize: 20 }}>Small Text</Text>
      </View>
</Text>
like image 83
Ali SabziNezhad Avatar answered Nov 05 '22 10:11

Ali SabziNezhad


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.

like image 33
Ravi Raj Avatar answered Nov 05 '22 10:11

Ravi Raj


you can also define the smallText lineHeight to match the bigText:

render() {
    return (
        <Text style={{ fontSize: 60 }}>
            Big Text
            <Text style={{ fontSize: 20, lineHeight:60 }}>
                Small Text
            </Text>
        </Text>
    );
}
like image 44
Daniel Givoni Avatar answered Nov 05 '22 10:11

Daniel Givoni