0

Learning React using a Udemy course. Ran into the error while trying to output state value:

import React, {Component} from 'react';

// Create a new component and make this component produce some HTML

class SearchBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            term: ''
        };
    };

    render() {
        return (
            <div>
                <input onChange={this.onInputChange}></input>
                Value of the input : {this.state.term}
            </div>
        );
    };

    onInputChange(event) {
        this.setState({term: event.target.value})
    }; }

export default SearchBar;

Could you please help explain the error?

  • 3
    This question has been asked and answer many times. Bind `this`, use arrow functions. Etc. – Andrew Li Oct 04 '17 at 12:18
  • https://stackoverflow.com/questions/32317154/uncaught-typeerror-cannot-read-property-setstate-of-undefined – HelenA Oct 04 '17 at 12:18

1 Answers1

0

add to your constructor

this.onInputChange = this.onInputChange.bind(this);

or use an arrow function in your HTML

<input onChange={e => this.onInputChange(e)}></input>

or use an arrow function in your class

onInputChange = (event) => { ... }

Kordon
  • 254
  • 2
  • 12