Trim white space means removing white spaces from the text input from both start and end. The following example shows how to trim white space from text input in ReactJS.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the validator module using the following command:
npm install validator
Project Structure: It will look like the following.
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React, { useState } from "react" ; import validator from 'validator' const App = () => { const [value, setValue] = useState( '' ) const validate = (inputText) => { setValue( "#" +validator.trim(inputText)+ "#" ) } return ( <div style={{ marginLeft: '200px' , }}> <pre> <h2>Trimming White Space in ReactJS</h2> <span>Enter Text: </span><input type= "text" onChange={(e) => validate(e.target.value)}></input> <br /> <span style={{ fontWeight: 'bold' , color: 'red' , }}>{value}</span> </pre> </div> ); } export default App |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
- The following will be the output if the user enters input without any space. You can see that the text remains as it is because there is no white space present in the input text.
- The following will be the output if the user enters input with white space from both the end. You can see that the final output text is trimmed from both the side by removing white space.
NOTE: In the above example, # is appended from both ends so that the user can see the result that white space is removed.