There are various types of components available in React Native. Each component has its unique task. Props are used to customize the components by giving them different parameters. Each component has its infrequent ability to customize the component.
For Example : In this tutorial we would going use component Image to show image in application and to gain control of Image, we would use Prop named as source . Source controls what shows inside Image component. Like we can show a local image or also can show image from HTTP URL.
Source Code for index.android.js file :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import React, { Component } from ‘react’;
import {
AppRegistry, Image
} from ‘react-native’;
export default class Myproject extends Component {
render() {
let Image_Http_URL ={ uri: ‘/wp-content/uploads/2017/06/sample_image.png’};
return (
<Image source={Image_Http_URL} style = {{height: 200, resizeMode : ‘center’, margin: 5 }} />
);
}
}
AppRegistry.registerComponent(‘Myproject’, () => Myproject);
|
Screenshot :
Next step is to make your own component with Props. So now we would make a single Text component and by using Props we can call it anywhere in our application with various styles.
Source Code for index.android.js file with own Props :
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
|
import React, { Component } from ‘react’;
import { AppRegistry, Text, View } from ‘react-native’;
class HelloClass extends Component {
render() {
return (
<Text style={{marginTop : 10}}>Hello {this.props.StudentName} !</Text>
);
}
}
export default class MyProject extends Component {
render() {
return (
<View style={{alignItems: ‘center’, marginTop : 20}}>
<HelloClass StudentName=‘Pankaj’ />
<HelloClass StudentName=‘Honey’ />
<HelloClass StudentName=‘Sumit’ />
</View>
);
}
}
// skip this line if using Create React Native App
AppRegistry.registerComponent(‘MyProject’, () => MyProject);
|
What we are doing in above code :
In above code we have created a extra class named as HelloClass. Inside that class we would create a Text component. Now we would set this component as Props using this.props.StudentName . The Prop value is Hello. Now we would call that Prop into our Main Myproject class View component using ClassName PropName .
Screenshot :