React native components did support the percentage(%) format like we have already seen in web applications, Developer can Set View Height Width in Percentage format Respect of Root View. It will automatically determine the Parent component height width and according to that it will set children view height width in both android and iOS react native applications.
Contents in this project Set View Height Width in Percentage format Respect of Root View in react native app:
1. Import Platform, StyleSheet, View and Text component in your project.
1
2
3
|
import React, { Component } from ‘react’;
import { Platform, StyleSheet, View, Text } from ‘react-native’;
|
2. Create a Root view in render’s return block, This would be our main View covert the complete application screen.
1
2
3
4
5
6
7
8
9
10
11
12
|
render()
{
return(
<View style = { styles.MainContainer }>
</View>
);
}
|
3. Creating a children View inside Root Parent View. We are using the inline CSS technique to implement CSS on child view. As you can see in below child view we are applying the Width and Height of view in percentage format in respect of Root View.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
render()
{
return(
<View style = { styles.MainContainer }>
<View style={{
width: ‘80%’,
height: ‘50%’,
backgroundColor: ‘#4CAF50’,
justifyContent: ‘center’,
alignItems: ‘center’
}}>
<Text style={{color: ‘#fff’, fontSize: 22}}> View in Percentage </Text>
</View>
</View>
);
}
|
4. Creating Style for Root View.
1
2
3
4
5
6
7
8
9
10
|
const styles = StyleSheet.create(
{
MainContainer:
{
flex: 1,
alignItems: ‘center’,
justifyContent: ‘center’,
paddingTop: ( Platform.OS === ‘ios’ ) ? 20 : 0
}
});
|
5. Complete source code for App.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
38
39
40
|
import React, { Component } from ‘react’;
import { Platform, StyleSheet, View, Text } from ‘react-native’;
export default class App extends Component<{}>
{
render()
{
return(
<View style = { styles.MainContainer }>
<View style={{
width: ‘80%’,
height: ‘50%’,
backgroundColor: ‘#4CAF50’,
justifyContent: ‘center’,
alignItems: ‘center’
}}>
<Text style={{color: ‘#fff’, fontSize: 22}}> View in Percentage </Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create(
{
MainContainer:
{
flex: 1,
alignItems: ‘center’,
justifyContent: ‘center’,
paddingTop: ( Platform.OS === ‘ios’ ) ? 20 : 0
}
});
|
Screenshot in android device:
Screenshots in iOS device: