Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - _this2.SetState is not a function

Tags:

reactjs

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

like image 391
Deano Avatar asked Sep 26 '16 14:09

Deano


People also ask

Why is setState not a function?

Cause of the error The reason why this error occurs is because of a concept called Closures in JavaScript. That means the scope/context of the function updateCounter and the class App are not the same. This means App and updateCounter have a different this .

How do you fix is not a function React?

The React. js "Uncaught TypeError: X is not a function" occurs when we try to call a value that is not a function as a function, e.g. calling the props object instead of a function. To solve the error, console. log the value you are calling and make sure it is a function.

How do I use setState in React?

The setState() Method State can be updated in response to event handlers, server responses, or prop changes. This is done using the setState() method. The setState() method enqueues all of the updates made to the component state and instructs React to re-render the component and its children with the updated state.

Can we use setState in componentDidMount?

You can call setState() immediately in componentDidMount() and triggers an extra rendering, but this happens before the browser updates the screen, calling render() twice.


2 Answers

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>
    );
  }
}
like image 166
Samu Avatar answered Oct 22 '22 03:10

Samu


you have to bind {event => this.SetState(event.target.value)} function to component this. problem is your onChange function not running your component this context

code should look something like this

const onChange = (event) => { this.setState({term:event.target.value}) }

 <input value={this.state.term} onChange={onChange.bind(this) />
like image 34
Balaji Thummalapenta Avatar answered Oct 22 '22 04:10

Balaji Thummalapenta