0
const SearchBar = createReactClass({
  getInitialState: () => {
    return { term: '' };
  },
  render: () => {
    return (
      <div>
        <input
          onChange={event => this.setState({ term: event.target.value })}
        />
      </div>
    );
  }
});

This gives me an error: "Cannot read property 'setState' of undefined" What did I do wrong?

I'm trying to use react in a more functional way. Is there any other way to this by the way? Preferably without using the keyword "this"?

  • 2
    Arrow functions *close over* `this` rather than having it defined by how they're called. They're not appropriate for use on prototypes. See also the related ES2015 class question and its answers: https://stackoverflow.com/questions/31095710/methods-in-es6-objects-using-arrow-functions Make those traditional functions (`render: function() {`) or methods (`render() {`) and it'll work. *(There's no effective difference between a property defined with a traditional function and a method if the method doesn't use `super`. There is if it does.)* – T.J. Crowder Jun 12 '18 at 10:46
  • Instead of render: () => use render: function() which will retain this context. I wouldnt bother with createClass which is older syntax. Definitely not functional either way, just different syntax. – jens Jun 12 '18 at 10:47
  • Thank you T.J.Crowder it's working. I feel kinda stupid now hahhaha @jens Is it older syntax? It's very active if you look at it. 1 milion downloads weekly for the create-react-class package And i've seen some people talking about the advantages and disadvantages like: https://toddmotto.com/react-create-class-versus-component/ Do you think it's outdated? Either way, do you think there is any way that I can code in React avoiding the "this" keyword? – Anthony White Jun 12 '18 at 11:14
  • You can use pure components to avoid ‘this’. I don’t think it’s worth tring to avoid ‘this’ conpletely. That article you posted is over 2 years old, so yes outdated. – jens Jun 12 '18 at 16:26

0 Answers0