Nic Bonetto
Nic Bonetto

Reputation: 543

React this.setState is undefined

This is an unfinished version of the class, but the finished version of class Typehead is supposed to print out a list of choices from props that match the input - basically an autocomplete function. The issue I am having is when I call the handleChange method, the error "cannot read property 'setState' of undefined" occurs. Here is the code:

import React from 'react'

export default class Typehead extends React.Component {
  constructor() {
    super()
    this.state = {}
  }

  handleChange(e) {
    this.setState(previousState => {
      previousState = e.target.value
      return {previousState}
    })
    console.log(this.state)
  }

  render() {
    return (
      <form>
        <div className="input-group">
          <label>
            Choose a Track:
            <input onChange={this.handleChange} type="text" 
            className="form-control" placeholder="Song Name"/>
          </label>
        </div>
      </form>
    )
  }
}

Any explanation as to why 'this' is undefined in handleChange would be greatly appreciated!

Upvotes: 2

Views: 7026

Answers (2)

Jaime Liz
Jaime Liz

Reputation: 136

The reason why is because the function context for event handlers gets assigned to the object which you're assigning the event handlers to... You have to explicitly bind the function or use an arrow function...

What I usually do is include this in the class constructor:

this.fn = this.fn.bind(this)

This will preserve the function context after it has been assigned as an event handler (arrow functions also keep context)

Hope this helps, I'm typing this on my phone's keyboard 😎

Upvotes: 2

Alex Borodin
Alex Borodin

Reputation: 2034

You should bind the component to handleChange. Try this:

  constructor() {
    super()
    this.state = {}
    this.handleChange = this.handleChange.bind(this);
  }

If you don't use it the handleChange recognizes 'input' as 'this' but not component.

Upvotes: 12

Related Questions