How to center Text in ReactNative both in horizontal and vertical?
I have an example application in rnplay.org where justifyContent=\"center\" and
Simple add
textAlign: "center"
in your styleSheet, that's it. Hope this would help.
edit: "center"
You can use two approaches for this...
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"
) .
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...
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>
)
}
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
You can use alignSelf
property on Text component
{ alignSelf : "center" }