0

I am trying to call parent method from child component, but it doesn't work and method in parent element is not triggered. In this example I have only two components where ChildHello calls method in Hello component.

codesandbox

Hello.tsx

import * as React from "react";

interface Props {
  itemClicked: () => void;
}

export class Hello extends React.Component<Props, {}> {
  constructor(props: Props) {
    super(props);
  }

  itemClicked = val => {
    console.log(val);
  };

  render() {
    const { name } = this.props;
    return <h1 itemClicked={this.itemClicked}>{this.props.children}</h1>;
  }
}

const styles = {
  height: "400px"
};

export class ChildHello extends React.Component<Props, {}> {
  constructor(props: Props) {
    super(props);
  }

  render() {
    return (
      <div onClick={this.props.itemClicked} style={styles}>
        <Hello>Hello Child</Hello>
      </div>
    );
  }
}
2
  • scope in parent use this.itemClicked.bind(this) Commented Dec 4, 2018 at 11:29
  • @Lostfields it didn't help Commented Dec 4, 2018 at 11:34

1 Answer 1

1

You need to understand parent child relationship in childHello you are using the click event.

 <div onClick={this.props.itemClicked} style={styles}>
        <Hello>Hello Child</Hello>
      </div>

childhello is called by the index.jsx page

 <div style={styles}>
    <ChildHello name="CodeSandbox" />
  </div>

Here you are not passing any click events. also, hello component is inside the child component which is wrong.

All the parent component should have click method involved and that method should be passed as props.

Like this

Parent:

<div style={styles}>
    <Hello name="CodeSandbox" />
  </div>

Hello component

render() {
    const { name } = this.props;
    return <ChildHello itemClicked={this.itemClicked} />;
  }

ChildHello

  render() {
    return (
      <div onClick={this.props.itemClicked} style={styles}>
        Hello
      </div>
    );
  }

Sandbox demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.