Input masking in React
๐
February 18, 2023
๐ReactJS
Today, we'll show you how to input masking in React. The `react-text-mask` package is a useful tool for formatting and validating user input in a text field, such as phone numbers, social security numbers, and credit card numbers.
Demo Application
Output - Input masking in React - Clue Mediator
Input masking in React
1. Project structure
-
react-input-masking
-
node_modules
-
public
- index.html
-
src
- App.js
- index.css
- index.js
-
package-lock.json
-
package.json
-
README.md
-
2. Package dependencies
Run the following command to install react-text-mask npm package.
npm i react-text-mask
You will find the version of the following packages in React application.
react
^18.2.0
react-text-mask
^5.5.0
3. Implementation
Refer to the following files for implementation.
App.js
import React, { useState } from 'react';
import MaskedInput from 'react-text-mask';
function App() {
const [value, setValue] = useState('');
return (
<div class="App">
<h4>Input masking in React - <a href="https://www.cluemediator.com">Clue Mediator</a></h4>
<maskedinput mask="{[/\d/," \d="" ,="" '-',="" ]}="" value={value} onchange="{(event)" ==""> setValue(event.target.value)}
placeholder="___-__-____"
guide={true}
showMask={true}
/>
</maskedinput></div>
);
}
export default App;
index.css
body {
margin: 20px;
font-family: Arial, Helvetica, sans-serif;
}
input {
width: 250px;
letter-spacing: 4px;
padding: 10px 15px;
border-radius: 10px;
border: 1px solid #999;
}
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<react class="strictmode">
<app>
</app></react>
);
4. Output
Run your application and check the output in the browser.
Live Demo
That's it for today.
Thank you for reading. Happy Coding..!!