How do i check if <input type="text"/> has only spaces in React JS?

Viewed 30

I need to get the value of a input to be displayed in real time but I need to show some default text if the Input is empty or only spaces, but I cant seem to get it to work

  const [productName, setProductName] = useState("");

  const defaultProductName = "Name";

  const handleChange = (event) => {
    setProductName(event.target.value);
    const inputValue = event.target.value;
    const inputId = document.getElementById("productNameInput").innerHTML;

    if (event.target.value.length == 0) {
      document.getElementById("productNameID").innerHTML = defaultProductName;
    } else {
      document.getElementById("productNameID").innerHTML = inputValue;
    }
  };
    <div className="productName" id="productNameID">
        {defaultProductName}
    </div>
    <form>
        <input type="text" id="productNameInput" onChange={handleChange} />
    </form>
1 Answers

you can try:

if(document.getElementByID("productNameInput").value == " " | document.getElementByID("productNameInput").value.length == 0){
    console.log("Input is empty")
}
Related