1

I'm updating a React component to use:

class SearchFilms extends React.Component

instead of:

var SearchFilms = React.createClass({

When I do run this, I get the following error: "Cannot read property 'setState' of undefined"

Could anyone suggest how I could update this?

class SearchFilms extends React.Component { 
//var SearchFilms = React.createClass({

    getInitial() {
        return {
            userInput: ''
        };
    }

    onChange(event) {
        this.setState({
            userInput: event.target.value
        });
        this.props.newVal(event.target.value);
    }

    render() {
        var languages = ['Shutter Island', 'Inception', 'Titanic', 'Blood Diamond'];

        return (
            <div className="row" id="Nav">
                <input type="text" 
                    value={this.props.userInput}
                    onChange={this.onChange}
                />
            </div>
        )       
    }

}
stevejcoates
  • 33
  • 1
  • 5
  • 1
    Possible duplicate of [Uncaught TypeError: Cannot read property 'setState' of undefined](http://stackoverflow.com/questions/32317154/uncaught-typeerror-cannot-read-property-setstate-of-undefined) – Lingaraju E V Apr 29 '17 at 11:42
  • you are switching from es5 to es6, in es6 you need to bind the function to use `this` keyword. to solve your issue put this line in the constructor: `this.onChange = this.onChange.bind(this)` it will work :) – Mayank Shukla Apr 29 '17 at 11:47

1 Answers1

7

your this in onChange is undefined, which is caused by not binding.

add these:

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

FYI,

Community
  • 1
  • 1
Wildsky
  • 412
  • 3
  • 8