0

I have one react Component1:

Component1.jsx

import React from "react";

export default class Component1 extends React.Component {
  render() {
    return <div onClick={() => this.props.clickHander()}> Click Me </div>;
  }
}

and another react Component2 which imports and uses Component1 and passes it a clickHandler along with data:

Component2.jsx

import React from "react";
import Component1 from "./Component1";

export default class Component2 extends React.Component {
  function1() {
    console.log("function1");
  }
  function2() {
    console.log("function1");
  }
  handleClick() {
    console.log(this);
    this.function1(); // function1 and function2 are not present on `this`
    this.function2(); // instead `this` contains `data` and `clickHandler`
  }
  render() {
    return <Component1 data={{ key: "val" }} clickHandler={this.handleClick} />;
  }
}

When I click on <div /> with text Click Me, handleClick gets called. However, inside this call, this does not contain function1 and function2. Instead when called, handleClick has this.data inside this.clickHandler.

You can see this in action in this codesandbox:

enter image description here

I definitely miss react basics here. What is the ideal / preferred / most react way to implement this?

MsA
  • 2,599
  • 3
  • 22
  • 47

0 Answers0