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?
A ViewChild is a decorator which is used when we want to access a child component inside the parent component, we use the decorator @ViewChild() in Angular. Here I have declared a variable name child as decorator @ViewChild(). As shown below we can access childMethod of child component inside the parent component.
To call a parent component method from the child component, we need to pass the changeName() method as a prop to the child component and access it as a props data inside the child component.
React. js allows us to use props (short form of property) to pass data from parent component to child component. We have to set props value inside the child component, while we embed it to the parent component.
With React, typically you only need to bind the methods you pass to other components. For example, <button onClick={this. handleClick}> passes this. handleClick so you want to bind it.
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> } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With