Skip to content
Advertisement

How to handle empty value in React form fields?

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement