React - clearing an input value after form submit React - clearing an input value after form submit reactjs reactjs

React - clearing an input value after form submit


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: ''    });}


Since you input field is a controlled element, you cannot directly change the input field value without modifying the state.

Also in

onHandleSubmit(e) {    e.preventDefault();    const city = this.state.city;    this.props.onSearchTermChange(city);    this.mainInput.value = "";  }

this.mainInput doesn't refer the input since mainInput is an id, you need to specify a ref to the input

<input      ref={(ref) => this.mainInput= ref}      onChange={this.onHandleChange}      placeholder="Get current weather..."      value={this.state.city}      type="text"    />

In you current state the best way is to clear the state to clear the input value

onHandleSubmit(e) {    e.preventDefault();    const city = this.state.city;    this.props.onSearchTermChange(city);    this.setState({city: ""});  }

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

<input      id="mainInput"      onChange={this.onHandleChange}      placeholder="Get current weather..."      type="text"    />

and update the value in state onChange and onSubmit clear the input using ref

 onHandleChange(e) {    this.setState({      city: e.target.value    });  }  onHandleSubmit(e) {    e.preventDefault();    const city = this.state.city;    this.props.onSearchTermChange(city);    this.mainInput.value = "";  }

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 set this.state.city to null:

onHandleSubmit(e) {  e.preventDefault();  const city = this.state.city;  this.props.onSearchTermChange(city);  this.setState({ city: '' });}