-1

Say I have a class component function like so which accesses the props

myFunction() {
   console.log(this.props)
}

if this component the renders a functional component inside it and I pass it down like so:

<MyFunctionalComponent onChange={this.myFunction} />

this then breaks saying cannot read props of undefined presumably because the concept of "this" isn't in functional land

is there an easy way to fix this except for a big refactor? or passing props in as arguments rather than this.

Red Baron
  • 7,181
  • 10
  • 39
  • 86
  • 5
    You need to bind `this` to the class method. Typically this is solved by not using a _method_ but by using a [public class field](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Public_class_fields) arrow function on the class. e.g. `myFunction = () => { ... }`. This is a common problem - https://reactjs.org/docs/handling-events.html – romellem Apr 14 '22 at 17:37
  • 1
    Note that it is unrelated to React, the [context is a feature of JavaScript](https://stackoverflow.com/q/3127429/1218980). – Emile Bergeron Apr 14 '22 at 17:41
  • ah my mistake that was a typo. I was using `this`. I have edited the question now. that isn't the solution – Red Baron Apr 14 '22 at 17:42
  • Note that the typo isn't what we were referring to. The function context must be preserved properly. – Emile Bergeron Apr 14 '22 at 17:43
  • Let's say you have `class Person{ constructor(name){ this.name = name } speak(){ return 'Hello ' + this.name } }` Then later `let bob = new Person('bob'); console.log(bob.speak());` That will work. This won't: `const speakMethod = bob.speak; console.log(speakMethod());` The reason why this doesn't work is the same reason why you are getting your error. See [MDN on _this_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#this_in_classes) for more details. – romellem Apr 14 '22 at 19:32

1 Answers1

0

You really answered your own question.

because you are working in a class Component, you have to use 'this.' to pass the method. What I would do is the following.

<MyFunctionalComponent onChange={() => this.myFunction()} />

DocCaliban
  • 784
  • 6
  • 13