Hi there Stackoverflowers,
I'm presented with a rather silly problem. I am in the process of creating my first React application and I have encoutered a little issue, where I am not able to clear my input value, after I submit a form. A tried googling this problem, found some similar threads here, but I was not able to resolve this. I do NOT want to change the state of my component/application, just to change the value of the input to an empty string. I tried clearing the value of the input in my onHandleSubmit function, but I got an error "Cannot set property 'value' of undefined".
I would appreaciate any help. Thanks in advance! :)
My code:
My SearchBar Component:
import React, { Component } from "react";
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {
city: ""
};
this.onHandleChange = this.onHandleChange.bind(this);
this.onHandleSubmit = this.onHandleSubmit.bind(this);
}
render() {
return (
<form>
<input
id="mainInput"
onChange={this.onHandleChange}
placeholder="Get current weather..."
value={this.state.city}
type="text"
/>
<button onClick={this.onHandleSubmit} type="submit">
Search!
</button>
</form>
);
}
onHandleChange(e) {
this.setState({
city: e.target.value
});
}
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.mainInput.value = "";
}
}
export default SearchBar;
You are having a controlled component where
input
value is determined bythis.state.city
. So once you submit you have to clear your state which will clear your input automatically.In your
onHandleSubmit
function, set your state to{city: ''}
again like this :Since you input field is a controlled element, you cannot directly change the input field value without modifying the state.
Also in
this.mainInput
doesn't refer the input since mainInput is anid
, you need to specify a ref to the inputIn you current state the best way is to clear the state to clear the input value
However if you still for some reason want to keep the value in state even if the form is submitted, you would rather make the input uncontrolled
and update the value in state
onChange
andonSubmit
clear the input usingref
Having Said that, I don't see any point in keeping the state unchanged, so the first option should be the way to go.
this.mainInput
doesn't actually point to anything. Since you are using a controlled component (i.e. the value of the input is obtained from state) you can setthis.state.city
to null: