59

I have two components. I want to call a method of the first component from the second component. How can I do it?

Here is my code.

First Component

class Header extends React.Component{

    constructor(){
        super();
    }

    checkClick(e, notyId){
       alert(notyId);
    }
}

export default Header;

Second Component

class PopupOver extends React.Component{

    constructor(){
        super();
        // here i need to call Header class function check click....
        // How to call Header.checkClick() from this class
    }

    render(){
        return (
            <div className="displayinline col-md-12 ">
                Hello
            </div>
        );
    }
}

export default PopupOver;
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Kushal Jain
  • 3,029
  • 5
  • 31
  • 48
  • Why do you want to do that? I don't think its good practice, it should break component pattern. You have enough plugins to manage events in one place: RxJS for example (Flux,Redux ...) – Maxim Shoustin Aug 24 '16 at 09:37
  • 1
    What do you mean by break component pattern ? – Kushal Jain Aug 24 '16 at 09:37
  • Much easier to reuse components when they are independent. If you want to achieve what you want - merge them and create one component. Consider case when you change parent component method name: after that you need to go over your project and change dependancies respectively. – Maxim Shoustin Aug 24 '16 at 10:11
  • You can check it out github.com/burakozturk16/pigeon – Phd. Burak Öztürk Nov 18 '21 at 00:15

3 Answers3

36

You can do something like this

import React from 'react';

class Header extends React.Component {

constructor() {
    super();
}

checkClick(e, notyId) {
    alert(notyId);
}

render() {
    return (
        <PopupOver func ={this.checkClick } />
    )
}
};

class PopupOver extends React.Component {

constructor(props) {
    super(props);
    this.props.func(this, 1234);
}

render() {
    return (
        <div className="displayinline col-md-12 ">
            Hello
        </div>
    );
}
}

export default Header;

Using statics

var MyComponent = React.createClass({
 statics: {
 customMethod: function(foo) {
  return foo === 'bar';
  }
 },
   render: function() {
 }
});

MyComponent.customMethod('bar');  // true
Mohit Verma
  • 1,620
  • 2
  • 20
  • 30
11

Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.

Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:

  • Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
  • add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
  • if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:

let counter = 0;
function handleInstantiate() {
   counter++;
}

constructor(props) {
   super(props);
   handleInstantiate();
}
Bloomca
  • 1,784
  • 13
  • 17
  • Thanks, but my both components are independent, on one depend upon other, I just need to call a function of one component from other just like we calling an static function of one java class from another class – Kushal Jain Aug 24 '16 at 10:28
  • If you need to call a `static` function, than it could be separated to just a function. So place this function to `utils` folder, and import it when you need it. If any state is involved, than passing down or external state management. – Bloomca Aug 24 '16 at 10:30
  • can you please give me an small example of it – Kushal Jain Aug 24 '16 at 10:32
  • I've updated the post. Basically, just declare it as a usual function, and invoke when you need it – there is no need to keep static methods inside classes (unless you write in OOP style, but it is generally discouraged in React community). – Bloomca Aug 24 '16 at 11:23
2

You could do this to call a method of the child component from the parent component.

import React from 'react';

class Header extends React.Component {

    constructor() {
        super();
        this.childComponentRef;
    }

    getChildComponent = (childComponent) =>  {

        this.childComponentRef = childComponent;
        this.childComponentRef.sayHi();
        
    }

    render() {
        return (
            <ChildComponent getChildComponent={this.getChildComponent} />
        )
    }
};

class ChildComponent extends React.Component {

    componentDidMount () {
        this.props.getChildComponent(this);
    }

    sayHi = () => {
        alert("hi");
    }

    render() {
        return (
            <div className="displayinline col-md-12 ">
                Hello
            </div>
        );
    }
}

export default Header;
Casper
  • 166
  • 9