Text component is the most basic component in react native applications and used to display text in apps. Occasionally developer needs to show the Text just middle of application screen . So using this tutorial you can easily place the Text Align in just center of android and iOS device screen.
Contents in this project Set Text Align Vertically Horizontally Center :
1. Start a fresh React Native project. If you don’t know how then read my this tutorial.
2. Add AppRegistry, StyleSheet, Text and View component in import block.
1
|
import { AppRegistry, StyleSheet, Text, View } from ‘react-native’;
|
3. Add View as parent view in render’s return block.
1
2
3
4
5
6
7
8
9
10
11
|
render() {
return (
<View>
</View>
);
}
|
4. Create custom css class named as MainContainer just above the AppRegistry.registerComponent line.
justifyContent: ‘center’ sets the View’s inside child component align Vertically center.
alignItems: ‘center’ sets the View’s inside child component align Horizontally center.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
const styles = StyleSheet.create({
MainContainer :{
// Setting up View inside component in Vertically center.
justifyContent: ‘center’,
// Setting up View inside component align horizontally center.
alignItems: ‘center’,
flex:1
}
});
|
5. Call the MainContainer class in View.
1
2
3
4
5
|
<View style={styles.MainContainer}>
</View>
|
6. Add Text component inside View . Using Inline CSS style setting up Text font size as 25 pixels and Font color as back using hex code.
1
2
3
4
5
6
|
<View style={styles.MainContainer}>
<Text style= {{ fontSize: 25, color: “#000” }}> Hello Friends </Text>
</View>
|
7. Complete source code of index.android.js / index.ios.js file :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
import React, { Component } from ‘react’;
import { AppRegistry, StyleSheet, Text, View } from ‘react-native’;
class Myproject extends Component {
render() {
return (
<View style={styles.MainContainer}>
<Text style= {{ fontSize: 25, color: “#000” }}> Hello Friends </Text>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer :{
// Setting up View inside component in Vertically center.
justifyContent: ‘center’,
// Setting up View inside component align horizontally center.
alignItems: ‘center’,
flex:1
}
});
AppRegistry.registerComponent(‘Myproject’, () => Myproject);
|
Screenshot: