In this article, we learn about how to call function from another class in react-native, as our project scope getting more this is more important to use another class, i.e. calling the method from parent to child and child to parent, to understand this create a new project and as we see below Class A (App.js) is parent class and ClassB (ClassB.js) is child class, in above example, we are going to call method from parent to child and vice versa.
I have created one components folder in the root directory, in that, I created another .js file which is our second classB, which will be going to render in App.js and then we will call the function on one to another and vice versa
1. Setup views (App.js)
Create ClassB.js in components folder in the root directory, and import this class in App.js like below
import React, {Component} from 'react'; import {Platform, StyleSheet, Text, View, TextInput, Alert, Button} from 'react-native'; import <strong>ClassB</strong> from '<span style="color: #ff0000;" data-mce-style="color: #ff0000;"><strong>.</strong></span>/components/ClassB';
If your parent view is in components folder then you have to put two dots in the path like below
import ClassB from '../components/ClassB';
After that, I just put this ClassB in render method of App.js as below
constructor(props) { super(props); this.state = { Usrname: '', }; } render() { return ( <View style={styles.container}> <Text style={styles.welcome}>Class A (App.js)</Text> <ClassB/> //<---- Like this <Text style={styles.welcome}>{this.state.Usrname}</Text> </View> ); }
To call a method in this App.js create one method name callbackFromB(data){ … } bind this method in the constructor like below:
constructor(props) { super(props); this.callbackFromB= this.callbackFromB.bind(this); this.state = { Usrname: '', }; } callbackFromB(data){ this.setState({ Usrname: data}); }
After this pass this callbackFromB method as a reference like this
1.ParentClass:
<ClassB ref={ref => (this.child = ref)} //<--- By using ref you can call child class method referenceCallback = {this.callbackFromB.bind(this)}/>
2.Child Class:
this.props.referenceCallback(data);
Let’s see the full code of App.js
/** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow */ import React, {Component} from 'react'; import {Platform, StyleSheet, Text, View,TextInput,Alert,Button,TouchableOpacity} from 'react-native'; import ClassB from './components/ClassB'; //import { Button } from 'react-native-elements'; export default class App extends Component{ constructor(props) { super(props); this.callbackFromB = this.callbackFromB.bind(this); this.state = { Usrname: '', }; } callbackFromB(data){ this.setState({ Usrname: data}); } callChildMethod=()=>{ this.child.childMethod(this.state.Usrname); //<--- Calling child class method } render() { return ( <View style={styles.container}> <Text style={styles.welcome}>Class A (App.js)</Text> <ClassB ref={ref => (this.child = ref)} //<--- By using ref you can call child class method referenceCallback = {this.callbackFromB.bind(this)}/> <TouchableOpacity onPress={this.callChildMethod}> <Text style={styles.welcome}>{this.state.Usrname}</Text> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#81D8D0', }, welcome: { fontSize: 40, textAlign: 'center', margin: 10, color: '#f96161', fontWeight: 'bold', }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, inputs:{ height:45, marginLeft:16, borderBottomColor: '#FFFFFF', flex:1, }, inputContainer: { borderBottomColor: '#05C203', backgroundColor: '#FFFFFF', borderRadius:5, borderBottomWidth: 1, width:350, height:45, marginBottom:20, flexDirection: 'row', alignItems:'center' }, });
Now let’s see the second ClassB where we call reference method referenceCallback from above App.js
2. components/ClassB.js
I have placed one TextInput in this js file we will call reference method onTextChange of TextInput and pass data through this method
1. Import the following component
import React, {Component} from 'react'; import {Platform, StyleSheet, Text, View,TextInput,Button,Alert} from 'react-native';
Then create method changeData and bind this method in the constructor as shown below
constructor(props) { super(props); this.changeData = this.changeData.bind(this); this.state = { Usrname: '', }; } changeData(data){ this.setState({Usrname: data}) this.props.referenceCallback(data); }
As you see above in changeData method firstly I save data in state and then pass this data to referenceCallback method which is previously passed from App.js Let’s see the full code of ClassB
import React, {Component} from 'react'; import {Platform, StyleSheet, Text, View,TextInput,Button,Alert} from 'react-native'; export default class ClassB extends Component<Props> { constructor(props) { super(props); this.changeData = this.changeData.bind(this); this.state = { Usrname: '', }; } changeData(data){ this.setState({Usrname: data}) this.props.referenceCallback(data); } childMethod(text){ console.log("++++++++ childMethod called "+text); } render() { return ( <View style={styles.container}> <Text style={styles.welcome}>Class B {"\n"} (ClassB.js)</Text> <View style={styles.inputContainer}> <TextInput style={styles.inputs} placeholder="Username" underlineColorAndroid='transparent' onChangeText={(email) => this.changeData(email)}/> </View> <Text style={styles.welcome}>{this.state.Usrname}</Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#1f44ff', }, welcome: { fontSize: 40, textAlign: 'center', margin: 10, fontWeight: 'bold', }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, inputs:{ height:45, marginLeft:16, borderBottomColor: '#FFFFFF', flex:1, }, inputContainer: { borderBottomColor: '#05C203', backgroundColor: '#FFFFFF', borderRadius:5, borderBottomWidth: 1, width:350, height:45, marginBottom:20, flexDirection: 'row', alignItems:'center' }, });
Output:-
Thank you.. 🙂 enjoy coding…
Heya i am for the first time here. I came across this board and I in finding It really useful & it helped me out a lot. I am hoping to give one thing back and aid others such as you aided me.
Thank you 🙂
Whats the meaning of the onRef in the code “<ClassB onRef={ref…"
JavaScript
(this.referenceCallback = ref)}
referenceCallback = {this.callbackFromB.bind(this)}/>
1
2
(this.referenceCallback = ref)}
referenceCallback = {this.callbackFromB.bind(this)}/>
Hi Nick, I had change source code please check
basically, I have added ref={ref => (this.child = ref)}, by using this you call method from child ClassB from Parent Class App.js
Please check the latest code for the same, Thank you 🙂