Input masking in React
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
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.
1 | npm i react-text-mask |
You will find the version of the following packages in React application.
3. Implementation
Refer to the following files for implementation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import React, { useState } from 'react'; import MaskedInput from 'react-text-mask'; function App() { const [value, setValue] = useState(''); return ( <div className="App"> <h4>Input masking in React - <a href="https://www.cluemediator.com">Clue Mediator</a></h4> <MaskedInput mask={[/\d/, /\d/, /\d/, '-', /\d/, /\d/, '-', /\d/, /\d/, /\d/, /\d/]} value={value} onChange={(event) => setValue(event.target.value)} placeholder="___-__-____" guide={true} showMask={true} /> </div> ); } export default App; |
1 2 3 4 5 6 7 8 9 10 11 12 | 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; } |
1 2 3 4 5 6 7 8 9 10 11 12 | 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.StrictMode> <App /> </React.StrictMode> ); |
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..!!