skip to Main Content

I have a simple number input in react component. I need to make it not accept more than 4 characters. But it doesn’t work with maxLength attribute. What else i can do to prevent it taking more than 4 characters.

<input type="number" onchange={handleChange} 

<input type="number"/>

/>

2

Answers


  1. you can add readonly attribute to the input when your hook gets 4 characters

    Login or Signup to reply.
  2. The handleChange function checks if the length of the input value is less than or equal to 4 before updating the state.

    import React, { useState } from "react";
    
    export default App = () => {
      const [inputValue, setInputValue] = useState("");
    
      const handleChange = (event) => {
        const newValue = event.target.value;
        if (newValue.length <= 4) {
          setInputValue(newValue);
        }
      };
    
      return (
        <div>
          <label htmlFor="fourCharInput">Enter up to 4 characters:</label>
          <input type="text" value={inputValue} onChange={handleChange} />
        </div>
      );
    };
    

    If you wanna play around with the code, here is the sandbox.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search