Deano Deano - 2 months ago 29
React JSX Question

React - _this2.SetState is not a function

I'm trying to create a component that will print out input text to the screen, here is what I'm working on.

class SearchBar extends Component {
constructor(props) {
super(props);

this.state = { term: '' };
}

render() {
return (
<div className="search-bar">
<input value={this.state.term} onChange={event => this.SetState(event.target.value)} />
The value of input is: {this.state.term}
</div>
);
}
}


However I keep getting an error in Chrome console:

bundle.js:19818 Uncaught TypeError: _this2.SetState is not a function


Any ideas?

Thanks

Answer

Try this:

class SearchBar extends Component {
  constructor(props) {
    super(props);
    this.state = { term: '' };
    this.setInputState = this.setInputState.bind(this);
  }
  
  setInputState(event) {
    this.setState({ term: event.target.value });
  }

  render() {
    return (
      <div className="search-bar">
        <input value={this.state.term} onChange={this.setInputState} />
        The value of input is: {this.state.term}
      </div>
    );
  }
}