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://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