Open In App

How to Trim White Spaces from input in ReactJS?

Last Updated : 04 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Trim white spaces from input removes the spaces from the start and end of the input string in react. The article covers how to remove whitespace from input in react.

Approach

To remove or trim the white spaces from the input in react we will use the validator npm package. Install the validator package and pass the input value to validator.trim function. It will remove the whitespaces and return the input string. We can also use JavaScript trim method.

Steps to Create 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.

Project Structure

The updated dependencies in the package.json file are:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"firebase": "^10.14.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-router-dom": "^6.26.2",
"react-scripts": "5.0.1",
"validator": "^13.12.0",
"web-vitals": "^2.1.4"
},

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
// Filename: App.js

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:

output---trim-white-spaces

NOTE: In the above example, # is appended from both ends so that the user can see the result that white space is removed.



Next Article

Similar Reads