How to handle empty value in React form fields?

Viewed 2710

Below code is taken from reactjs.org, my question is how to handle the empty value in the below code. Alert should trigger only when there is some input from the user, it should not trigger if the input is empty

 class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

ReactDOM.render(
  <NameForm />,
  document.getElementById('root')
);
1 Answers

you should use an if statement at your handleSubmit function

  handleSubmit(event) {
   if(this.state.value){
    alert('A name was submitted: ' + this.state.value);
   }
    event.preventDefault();
  } 

this way if value is equal to '' alert would not be shown if it contains any character such as 'm' it would show the alert

Related