How to add minlength in react js?

Hi Friends πŸ‘‹,

Welcome To aHoisting!

To add minlength in react js, you can use minLength={5} in <input/>. It will add minlength in react js.

Today, I am going to show you, how to add minlength in react js.

Table of contents

  • Install and create a new React app.
  • Import react component.
  • Create a Component.

Let’s start with the first step.

Step 1: Install and create a new React app.

First you have to install the React project. You should use create-react-app command to create a new React project.

npx create-react-app my-app
cd my-app
npm start

Step 2: Import react component.

After installing, you have to import your React component.

import React, { useState } from 'react';

Step 3: Create a Component.

You can use minLength={5} in <input/> to add minlength in react js.

<form onSubmit={handleSubmit}>
  <label>
    Enter text (minimum 5 characters):
      <input
          type="text"
          value={inputValue}
          onChange={handleChange}
          minLength={5}
          required
      />
    </label>
  <button type="submit">Submit</button>
</form>

Add minlength example.

The below code is an example of a React. You have to import React and set minLength={5} in <input/> to add minlength in react js.

App.js

import React, { useState } from 'react';

const App = () => {
  const [inputValue, setInputValue] = useState('');

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

  const handleSubmit = (event) => {
    event.preventDefault();
    // Handle form submission
    console.log('Form submitted with value:', inputValue);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Enter text (minimum 5 characters):
        <input
          type="text"
          value={inputValue}
          onChange={handleChange}
          minLength={5}
          required
        />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
};

export default App;

In the above code example, I have used the minLength={5} to add minlength in react js.

Check the output of the above code.

React, add, add, minlength

All the best πŸ‘