Set string length limit in MUI textfield in React JS

In this blog, we’ll learn more about the features of the textfield component of MUI. As we know, textfield component is just the customized input component for taking input from the user. MUI adds some more features, as compared to the pure html input tag, to make it easy for the developers. One such feature is to set a word limit in the textfield.

Use Case

When making forms in React applications using Material-UI, restricting the length of input strings is a common requirement. Examples of such scenarios can be – limiting usernames, passwords, or some descriptions to ensure consistency in the database. Probably, you too have faced the word limit while filling out forms or posting comments in live chat on YouTube! Let’s learn.

Prerequisites

This tutorial assumes you have a basic understanding of React and have a React project set up. If you haven’t installed Material-UI in your project, you can do so by running:

npm install @mui/material @emotion/react @emotion/styled

Implementing the Limit

The inputProps property of the TextField component is used to set the maxLength attribute to a preferred length, restricting the input to that many characters.
Let’s understand with a simple example:

1. Create a react component

import { useState } from "react";
import TextField from "@mui/material/TextField";

const LimitedInput = () => {
  const [value, setValue] = useState("");

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  return (
    <>
      <TextField
        label="Limited Input"
        value={value}
        onChange={handleChange}
        variant="outlined"
        fullWidth
        inputProps={{ maxLength: 15 }} // Setting the maximum length
      />
      <p style={{color: "red"}}>Word Count: {value.length}</p>
    </>
  );
};

export default LimitedInput;


2. Import the component in App

import LimitedInput from "./components/LimitedInput";

export default function App() {
  return (
      <LimitedInput />
  );
}

Output :

Set string length limit in MUI textfield in React JS

 

So, as we can see in the code, the length of the value of input field can’t cross 15 because of the maxLength set to 15. Additionally, I have displayed the word count of the input by rendering the length of value string.

Conclusion

So, we learned that limiting the string length in an MUI TextField in React can be achieved by using the inputProps property and the maxLength attribute. You can now ensure a consistent and limited input length, creating a better user experience in your app. That’s it from today’s blog.

Leave a Reply

Your email address will not be published. Required fields are marked *