React - _this2.SetState is not a function
Sophia Terry
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 functionAny ideas?
Thanks
18 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> ); }
} 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) /> I think you need to bind your this, try this (no pun intended).
render() { return ( <div className="search-bar"> <input value={this.state.term} onChange={event => this.setState.bind(this, event.target.value)} /> The value of input is: {this.state.term} </div> ); } 2 I believe you had to specify what was changed in the state:
this.setState({ term: event.target.value });instead of
this.setState( event.target.value ); Try this code:
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({term:event.target.value})} /> The value of input is: {this.state.term} </div> ); }
} This worked for me. I think you missed out on the state key name term and also this SetState, which should be setState. Just follow my example below am sure it will work for you also.
class Square extends React.Component {
constructor(props){ super(props) this.state = { value: null };
}
render() { return ( <button className="square" onClick={()=> this.setState({value:'X'})}> {this.state.value} </button> );
}
} 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> ); }
}you wrote SetState instead of
I faced a similar problem and noticed that I was using this.state.setState() method instead of this.setState().
Although OP's problem is the wrong capitalization.