Ryan Ryan - 1 month ago 5
React JSX Question

Why is this undefined in function when calling .bind(this)?

In my component, I'm calling a function defined in another file like this:

import React from 'react';
import { widgetComponentDidMount } from "../../SharedData/widget";

export default class Component extends React.Component {

constructor(props) {
super(props);
};

componentDidMount(){
widgetComponentDidMount(this).bind(this);
}

//render, etc

};


But when I put a debugger into the function's definition, "this" is undefined:

export function widgetComponentDidMount() {
var _this = this;
debugger
//_this is undefined
}


I know I can pass this as an argument and reference it that way, but I'd rather avoid having to pass it every time. Isn't that the purpose of bind? I've only ever been able to use it within the same file. Any ideas why it's undefined and how I can access "this" without passing it as an argument?

Answer

You're executing the function before you call bind. You'd have to bind before executing:

widgetComponentDidMount.bind(this)();

If it were me, I'd actually perform the bind in the constructor method and store the result so you don't need to create a new function for each call:

export default class Component extends React.Component {

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

  componentDidMount() {
    this.widgetComponentDidMount();
  }
}
Comments