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>
        )       
    }

}
2
  • 1
    Possible duplicate of Uncaught TypeError: Cannot read property 'setState' of undefined Commented Apr 29, 2017 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 :) Commented Apr 29, 2017 at 11:47

1 Answer 1

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,

Sign up to request clarification or add additional context in comments.

1 Comment

This works great - thank you! I can see where I went wrong now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.