React.js – TypeError: Cannot read property ‘setState’ of undefined

Read Time:1 Minute, 0 Second

Problem code

import React from "react"

class SearchInput extends React.Component {
  state = { q: "" }

  onInputChange(e) {
    this.setState({ q: e.target.value })
  }

  render() {
    return (
      <div>
        <form>
          <input type='text' name='search' placeholder='Search ...' onChange={this.onInputChange} />
        </form>
      </div>
    )
  }
}

export default SearchInput

Error

TypeError: Cannot read property 'setState' of undefined
onInputChange
src/components/SearchInput.js:11

Solution

https://stackoverflow.com/questions/32317154/react-uncaught-typeerror-cannot-read-property-setstate-of-undefined

https://reactjs.org/docs/handling-events.html

With ES5

import React from "react"

class SearchInput extends React.Component {
  constructor(props) {
    super(props)
    this.state = { q: "" }

    this.onInputChange = this.onInputChange.bind(this)
  }

  onInputChange(e) {
    this.setState({ q: e.target.value })
  }

  render() {
    return (
      <div>
        <form>
          <input type='text' name='search' placeholder='Search ...' onChange={this.onInputChange} />
        </form>
      </div>
    )
  }
}

export default SearchInput

With ES6

import React from "react"

class SearchInput extends React.Component {
  state = { q: "" }

  onInputChange = (e) => {
    this.setState({ q: e.target.value })
  }

  render() {
    return (
      <div>
        <form>
              <input type='text' name='search' placeholder='Search ...' onChange={this.onInputChange} />
        </form>
      </div>
    )
  }
}

export default SearchInput

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.