codewithjohn.dev
Published on

How to Check if an Input is Empty in React

Sometimes it is good practice to check the value of input before submitting a form; this helps improve the user experience and prevent errors. So to check if an input is empty in React

  • First We need to get the value of the field

  • Call the trim() method on the field's value

  • Check the length property on the value.

If the field's value has a length of 0, then the field is empty, otherwise it isn't.

example_one.js
import React, { useState } from 'react';

function MyComponent() {
  const [inputValue, setInputValue] = useState('');

  // Event handler for input change
  const handleInputChange = (event) => {
    setInputValue(event.target.value);
  };

  // Function to handle form submission
  const handleSubmit = (event) => {
    event.preventDefault();

    // Check if input is empty
    if (inputValue.trim().length === 0) {
      alert('Input cannot be empty!');
    }
    else {
      alert('input value is NOT empty', inputValue);
      // Perform further actions with the input value
      // ...
    }


  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" value={inputValue} onChange={handleInputChange} />
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyComponent;


We used the trim() method to remove any leading or trailing whitespace from the field's value. The trim method removes any unnecessary leading or trailing whitespaces from a string. So after trimming the value of the field, we checked for the length. If the length is zero, then the field is empty.