Reputation: 1273
I'm pretty new to React. I have a simple app where text is entered into an input field and then sent to a server when a button is clicked. How can I get the value of the input field? This is incredbily easy in jQuery but I can't figure it out with React.
Here's my code:
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props){
super(props)
this.state = {
terms: ''
}
this.updateTerms = this.updateTerms.bind(this);
}
updateTerms(evt) {
this.setState({
terms: evt.target.value
})
}
search() {
alert(this.state.terms)
}
render() {
const btn1 = {
width: '100%',
backgroundColor: 'white'
}
return (
<div className= 'wrapper'>
<div className= 'item1'>
Specials Fact Tree Demo
</div>
<div className= 'item2'>
Search Term(s):<br/>
<input className= 'form-control' type="text" onChange={this.updateTerms} />
<br/>
<div id = 'results' >
<div id='resultsWrap' >
<select className= 'form-control' id= 'styles' ></select>
<select className= 'form-control' id= 'similar' ></select>
<div id= 'attsDiv' className= 'form-control' >
<dl id= 'atts'></dl>
</div>
</div>
</div>
<button className="btn btn-default" style = {btn1} id= 'search' onClick={this.search}>Search</button>
<div id="activeTraining" >
</div>
</div>
</div>
);
}
}
export default App;
Any help would be greatly appreciated. Plus, easy points!
Upvotes: 1
Views: 72
Reputation: 1119
If you are already familar with ECMAScript 6 you can just use arrow functions and save on the bindings like:
search = () => {
alert(this.state.terms)
}
Upvotes: 0
Reputation: 31024
You forgot to bind the search
method as well (inside the constructor):
this.search = this.search.bind(this);
Upvotes: 1