TommyVee TommyVee - 1 year ago 202
Javascript Question

React - clearing an input value after form submit

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;

Answer Source

You are having a controlled component where input value is determined by this.state.city. So once you submit you have to clear your state which will clear your input automatically.

onHandleSubmit(e) {
    e.preventDefault();
    const city = this.state.city;
    this.props.onSearchTermChange(city);
    this.setState({
     city: ''
   });
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download