2

I've got a parent component which feeds a onSomeAction prop to a child component:

export default class myComponent extends Component {

    constructor(props) {
        super(props);
    }

    render() {
        return (
           <div className="mycomponent">
             <ChildComponent onSomeAction={this.doSomething} />
           </div>
        )
    }

    doSomething() {
        console.log(this);
    }
}

In the child component when something is clicked on I'm calling a method whiih in turns calls the onSomeAction prop:

export default class ChildComponent extends Component {
    render() {
        return (
           <div className="">
             <a onClick={() => this.doIt()}>doIt</a>
           </div>
        )
    }

    doIt() {
        const { onSomeAction } = this.props;
        onSomeAction();
    }
}

The problem I'm seeing is back in the parent component the this context seems to have been lost - the console.log in the doSomething method returns undefined. Why is this? I need to be able to access the parent component context.

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
Mike Rifgin
  • 10,409
  • 21
  • 75
  • 111
  • Possible duplicate of [How to access the correct \`this\` / context inside a callback?](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – Felix Kling Jan 29 '16 at 16:10

3 Answers3

5

You need set context in parent component, you can do it with .bind

<ChildComponent onSomeAction={ this.doSomething.bind(this) } />
                                               ^^^^^^^^^^^^   

Example

Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
0

There are two options for you on how you can get the element that has been clicked or the whole component scope this.

option one: instead of logging this you should logg the event target like so:

    doSomething(e) {
        console.log(e.target);
    }

option two: you have to attach the this keyword to the doSomething method like so:

constructor(props) {
    super(props);
    this.doSomething = this.doSomething.bind(this);
}

That was you'll be able to access the keyword this in your do something method.

Option3:

If you want to refer with this to the child component then you have to bind(this) on the function call int he child component

noa-dev
  • 3,561
  • 9
  • 34
  • 72
0

Actually you can fix it 3 ways:

  1. <ChildComponent onSomeAction={ this.doSomething.bind(this) } />

  2. <ChildComponent onSomeAction={ () => this.doSomething() } />

  3. <ChildComponent onSomeAction={this.doSomething} /> and add this to constructor: this.doSomething = this.doSomething.bind(this)

challenger
  • 2,184
  • 1
  • 18
  • 25