How to call function from another class in react-native

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

If your parent view is in components folder then you have to put two dots in the path like below

After that, I just put this ClassB in render method of App.js as below

To call a method in this App.js create one method name  callbackFromB(data){ … } bind this method in the constructor like below:

After this pass this callbackFromB method as a reference like this

1.ParentClass:

2.Child Class:

Let’s see the full code of App.js

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

Then create method changeData and bind this method in the constructor as shown below

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

Output:-

 

Call method from parent to child and child to parent react-native
Call method from parent to child and child to parent react-native

Thank you.. 🙂 enjoy coding…

4 Replies to “How to call function from another class in react-native”

  1. 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.

  2. 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)}/>

    1. 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 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *