In this article, we will learn how can we restrict the user to enter characters up to a certain limit.
Prerequisites: Knowledge about reactJs
Creating React Application:
Step 1: Create the react project folder, open the terminal, and write the command npm create-react-app folder name, if you have already installed create-react-app globally. If you haven’t then install create-react-app globally by using the command npm -g create-react-app or can install locally by npm i create-react-app.
npm create-react-app project
Step 2: After creating your project folder(i.e. project), move to it by using the following command.
cd project
Project Structure:
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.
In App.js file, we are creating a simple input element, to put a name with maxLength set to 10.
App.js
function App() { return ( <div className= "App" > <label >Name:</label> <input name= "name" type= "text" maxLength={10}/> </div> ); } export default App; |
To run the application: Run the application using the following command from the root directory of the project.
npm start
Output:
We can see that after the 10th character we cannot further add anything.
Approach 2: Creating an onChange function: In this approach, We are creating a simple form component that asks the user to enter their username, the moment the character length exceeds more than 10 an alert will be shown.
In this file, we are using useState a react-hook to maintain the state userName. We will create a function handleChange that will track the length of the user of the character is putting, here ‘e’ is the browser event. If it is equal to 10 then the alert will pop up or else it will be added to the state.
App.js
import React,{useState} from "react" ; const Form= () => { const [userName, setuserName] = useState( "" ); const handleChange =(e)=>{ // Here we are checking if the length is equal to 10 if (e.target.value.length===10){ window.alert( "Username shouldn't exceed 10 characters" ) } setuserName(e.target.value); } return ( <div> <label> Please enter username: </label> <input name= "username" value={userName} onChange={ handleChange} /> </div> ) } function App() { return ( <div className= "App" > <h1>Hey! Geek Welcome</h1> <Form/> </div> ); } export default App; |
To run the application: Run the application using the following command from the root directory of the project.
npm start