How to fix the maxlength attribute not working issue with React?

Sometimes, we want to fix the maxlength attribute not working issue with React.

In this article, we’ll look at how to fix the maxlength attribute not working issue with React.

How to fix the maxlength attribute not working issue with React?

To fix the maxlength attribute not working issue with React, we should make sure the input’s type attribute is set to text.

Also, we should set the maxLength prop to set the maxlength attribute.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [message, setMessage] = useState();

  const handleChangeInput = (e) => {
    setMessage(e.target.value);
  };

  return (
    <div>
      <input
        onChange={handleChangeInput}
        value={message}
        type="text"
        name="phone"
        maxLength="10"
      />
    </div>
  );
}

We add an input that with the maxlength attribute set to 10 to make sure the input value has never more than length 10.

The maxLength prop sets the value of the maxlength attribute of the input.

Also, we set the type attribute of the input to text to make sure maxlength is enforced.

Then we set the onChange and value props to the event handler function and value respectively.

Now we should see that we can’t enter more than 10 characters into the input.

Conclusion

To fix the maxlength attribute not working issue with React, we should make sure the input’s type attribute is set to text.

Also, we should set the maxLength prop to set the maxlength attribute.