Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check Input as its being typed ReactJS

I would like to check an input as it’s being typed, without pressing a key or a button asynchronously.I would like to set a variables value to true if a person has typed more than 4 letters.

I think it would also be fine if the value sets to true (if the value is 4 or more letters) after the user clicks outside the inputbox , but I prefer the former

Mock Code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var hasTypedMoreThan4Letters = false; //changes to true when more than 4 letters are typed in inp1

<input type="text" className="input1" id="inp1" onChange={onTypingMoreThan4Letters}/>

Not sure if it helps but Mock Image below

Mock Image

>Solution :

You need controlled components(controlled input). Here is my version using hooks. You get the number of symbols entered in count variable.

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);
  function handleInput(e) {
    setInput(e.target.value);
    setCount((prev) => prev + 1);
  }
  const [input, setInput] = useState("");
  return (
    <div className="App">
      <input value={input} onInput={handleInput} />
      <p>{count}</p>
    </div>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading