user94628 user94628 - 1 month ago 16
React JSX Question

React - Call parent method in child component

I have a parent and child compoents and I want to call a parent method in the child component like this:

import Parent from './parent.js';
class Child extends React.Component {
constructor(props) {
super(props);
};

click() {
Parent.someMethod();
}

render() {
<div>Hello Child onClick={this.click}</>
}
}

class Parent extends React.Component {
constructor(props) {
super(props);
};

someMethod() {
console.log('bar');
}

render() {
<div>Hello Parent</>
}
}


This returns an error message:

Uncaught TypeError: _Parent2.default.someMethod is not a function


How can this parent method be called in the child component?

Answer

Try this. Passing the function down as props to the child component.

import Parent from './parent.js';
class Child extends React.Component {
    constructor(props) {
        super(props);
        };

    click = () => {
        this.props.parentMethod();
    }

    render() {
          <div onClick={this.click}>Hello Child</div>
    }
}

class Parent extends React.Component {
    constructor(props) {
        super(props);
        };

    someMethod() {
        console.log('bar');
    }

    render() {
          <Child parentMethod={this.someMethod}>Hello Parent, {this.props.children}</Child>
    }
}
Comments