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
Needed Output
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.
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>
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.
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>
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With