Refer another component methods in React

it is very common for us to require a second component controller to access its methods from first component in Angular JS. The framwork does it for us when we use require in our component. My question here is do we have something similar in React, or how can we achieve the same thing in React ? Sample code snippet that I am talking about is below.

angular.module('demoModule', [])
.component('demoComponent1', {
  require: {
    anotherComponent: '^anotherCompoent'
  },
  controller: function() {
    this.$onInit = function() {
      this.anotherComponent.someMethod(this);
      console.log(this);
    };
  },
  templateUrl: 'sample.html'
});

Suggestions are appreciated with thanks.

1 thought on “Refer another component methods in React”

  1. You can utilize the ref attribute for what you wish to achieve here. When you assign a component a ref, its current attribute will be your custom component:

     class Parent extends React.Class {
        constructor(props) {
            this._child = React.createRef();
        }
    
        componentDidMount() {
            console.log(this._child.current.someMethod()); // Prints 'bar'
        }
    
        render() {
            return (
                <div>
                    <Child ref={this._child} />
                </div>
            );
        }
    }
    

    Note: This will only work if the child component is declared as a class, as per documentation found here: https://facebook.github.io/react/docs/refs-and-the-dom.html#adding-a-ref-to-a-class-component

    You can utilize componentDidMount() thats similar to that of the magic method $onInit in angular.

    Reply

Leave a Comment