Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call parent method in a child React 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?

like image 418
user94628 Avatar asked Oct 18 '16 13:10

user94628


People also ask

How do you call parent to child components?

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.

How do you call the parent component method from the child functional 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.

How do you get parent data from a child in react?

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.

How do you pass methods to child components in react?

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.


1 Answers

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>     } } 
like image 111
Martin Dawson Avatar answered Sep 16 '22 15:09

Martin Dawson