Bill
Bill

Reputation: 5150

React TypeScript: How to clear an input field

const emailInput = document.getElementById("loginEmail");
emailInput.value = ''
...
<input
  id="loginEmail"
  value={state.email}
  type="input" 
  className="input-text" 
  name="email" 
  placeholder={txt.emailAddress}
  onChange={formValue}
></input>

The error I'm getting on line 2 in the example above is `Property 'value' does not exist on type 'HTMLElement'.ts(2339)

`

Upvotes: 0

Views: 9783

Answers (2)

user11910739
user11910739

Reputation:

You have to assign the value for input element. To clear the value just reset the state variable.

this.setState({ email: "" });

Here is the small code for you

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputVal: "Clue Mediator"
    };
    this.onInputChange = this.onInputChange.bind(this);
    this.clearInput = this.clearInput.bind(this);
  }

  clearInput() {
    this.setState({ inputVal: "" });
  }

  // handle input change event
  onInputChange(e) {
    this.setState({ inputVal: e.target.value });
  }

  render() {
    return (
      <>
        <input
          placeholder="Enter your value here..."
          value={this.state.inputVal}
          onChange={this.onInputChange}
        />
        <input type="button" value="clear" onClick={this.clearInput} />
      </>
    );
  }
}

Here is the working demo for you
https://codesandbox.io/s/autumn-darkness-rybj2

Hope this will work for you!

Upvotes: 0

Przemek Struciński
Przemek Struciński

Reputation: 5228

This is how you should control the value of input in React

<input
  id="loginEmail"
  value={this.state.email}  
  type="input" 
  className="input-text" 
  name="email" 
  placeholder={txt.emailAddress}
  onChange={formValue}
></input>

In order to clear a value:

this.setState({
  email: ''
});

Upvotes: 2

Related Questions