1

I'm trying to call other functions in React.createClass functions but it doesn't work for some reason, I'm getting Cannot read property 'test' of undefined

var WallFeed = React.createClass({
    test: () => {
        console.log('hello world');
    },
    componentDidMount: () => {
        this.test();
    },
    render: () => {
        return (
            <div>test</div>
        );
    }
});

now, how can I call this.test() from componentDidMount (React's build in function) ?

thanks!

Ross Allen
  • 43,772
  • 14
  • 97
  • 95
greW
  • 1,248
  • 3
  • 24
  • 49
  • 1
    Why don't you uses es6 classes for react development as the react community as said to remove the support for React.createClass? – Shubham Jain Aug 01 '17 at 16:11

1 Answers1

2

Don't use arrow functions in the object literal passed to createClass. Arrow functions in object literals will always be called with window as this. See Arrow Function in object literal for an explanation:

var WallFeed = React.createClass({
    test() {
        console.log('hello world');
    },
    componentDidMount() {
        this.test();
    },
    render() {
        return (
            <div>test</div>
        );
    }
});
Ross Allen
  • 43,772
  • 14
  • 97
  • 95
  • 1
    The problem at hand has nothing to do with React autobinding methods. Autobinding is useful for methods that are used as event handlers, but none of the methods is used as event handler. – Felix Kling Aug 02 '17 at 06:28
  • @FelixKling Aha good point, thanks for pointing that out. I'll remove the mention of autobinding from the answer. – Ross Allen Aug 02 '17 at 14:57