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
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 .
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.
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.
You can call setState() immediately in componentDidMount() and triggers an extra rendering, but this happens before the browser updates the screen, calling render() twice.
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>
);
}
}
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) />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With