Hello Friends, As we all know react native’s new functional component structure is spreading very fast among developers because of their simple way of coding. Many of us new beginner developer doesn’t know how to call a method or function in functional component because our main Component is by default functional component. There are some changes between both class and functional component. Buttons and functions are the base of every react native application because using them we can set Click functionality and set onPress events to perform a certain task. So in this tutorial we would React Native Call Function in Functional Component Android iOS Example Tutorial.
Content in this project React Native Call Function in Functional Component Android iOS Example Tutorial:
1. Open your project’s main App.js file and import View, StyleSheet, Button and Alert component.
1
2
3
|
import React from ‘react’;
import { View, StyleSheet, Button, Alert } from ‘react-native’;
|
2. Creating our main export default function FirstApp(). This is our main Root functional component .
1
2
3
4
5
|
export default function FirstApp() {
}
|
3. Creating a Constant function named as showMessage() with Fat arrow syntax known as =()=> . We must have to use the fat arrow syntax in order to use the methods in functional component. Inside this function we would simply display a Alert dialog box.
1
2
3
4
5
|
const showMessage=()=>{
Alert.alert(‘Function Called…’) ;
}
|
4. Creating return() block to display UI components on the screen. Inside it we would Make a Root View component and 1 Button component. On button onPress event we would call the showMessage() method.
1
2
3
4
5
6
7
8
9
|
return (
<View style={styleSheet.MainContainer}>
<Button onPress={showMessage} title=“Click Here To Call Function in Functional Component” />
</View>
);
|
5. Creating Style.
1
2
3
4
5
6
7
8
9
10
11
|
const styleSheet = StyleSheet.create({
MainContainer: {
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’,
backgroundColor: ‘#FAFAFA’,
padding: 10
},
});
|
7. 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
|
import React from ‘react’;
import { View, StyleSheet, Button, Alert } from ‘react-native’;
export default function FirstApp() {
const showMessage=()=>{
Alert.alert(‘Function Called…’) ;
}
return (
<View style={styleSheet.MainContainer}>
<Button onPress={showMessage} title=“Click Here To Call Function in Functional Component” />
</View>
);
}
const styleSheet = StyleSheet.create({
MainContainer: {
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’,
backgroundColor: ‘#FAFAFA’,
padding: 10
},
});
|
Screenshots: