How to usemaxLength in ReactJS

We will use maxLength attribute for our input. It is the same as the maxlength attribute used for HTML. It restricts the user to enter characters till it reaches the maxLength limit that we have set.

Example: This example uses max legth attribute to implement the restriction for character input.

Javascript




// Filename - App.js
 
function App() {
    return (
        <div className="App">
            <label>Name:</label>
            <input name="name" type="text" maxLength={10} />
        </div>
    );
}
 
export default App;


Step to run the application: Run the following command to start your app in your localhost:3000.

npm start

Output: This output will be visible on the http:// localhost:3000 on the browser window.

We can see that after the 10th character we cannot further add anything.

How to restrict user character input limit in ReactJS ?

To restrict the user character input limit in React JS we can simply set a max input limit to the input box or we can also monitor the input length and make a custom function to set the restriction.

Similar Reads

Pre-requisite:

NPM & Node.js React.js React Hooks HTML onchange Event...

Steps to Create React Application:

Step 1: Go to your command prompt and write the below command to create a react app....

Approach 1: Using maxLength

We will use maxLength attribute for our input. It is the same as the maxlength attribute used for HTML. It restricts the user to enter characters till it reaches the maxLength limit that we have set....

Approach 2: using onChange event

...