Reputation: 11812
I am new in ReactJS and trying to get the search input box value and store it in a state.
My code:
<form className="search-form" onSubmit={this.handleSubmit}>
<input type="search" name="search" ref={(input) => this.query = input}
placeholder="Search..." />
<button className="search-button" type="submit" id="submit">Go!</button>
</form>
Inside constructor:
this.handleSubmit = this.handleSubmit.bind(this);
And
handleSubmit = e => {
e.preventDefault();
this.setState({search: this.query.value});
console.log(this.state.search) //Returns undefined
e.currentTarget.reset();
}
Any help is highly appreciated.
Upvotes: 3
Views: 1288
Reputation: 169
This code may help you:
import React from 'react';
class search extends React.Component{
constructor(props)
{
super(props);
this.state = {value: ''};
this.addValue = this.addValue.bind(this);
this.updateInput = this.updateInput.bind(this);
}
addValue(evt)
{
evt.preventDefault();
if(this.state.value !==undefined)
{
alert('Your input value is: ' + this.state.value)
}
}
updateInput(evt){
this.setState({value: evt.target.value});
}
render()
{
return (
<form onSubmit={this.addValue}>
<input type="text" onChange={this.updateInput} /><br/><br/>
<input type="submit" value="Submit"/>
</form>
)
}
}
export default search;
Upvotes: 0
Reputation: 41893
I would suggest you to use controlled input approach.
state = {
value: null,
}
handleValue = (e) => this.setState({ value: e.target.value });
Then you don't have to use ref
.
<input
type="search"
name="search"
onChange={this.handleValue}
placeholder="Search..."
/>
Upvotes: 1