In an extremely simple way, apply input masks to your React project.
input-mask-react is a package for react that was created with the purpose of facilitating software development. Applying input masks is a common and often repetitive task, come to think of it, input-mask-react makes this process simpler for you.
npm install input-mask-react
import { InputMask } from 'input-mask-react'
The example below shows how to create a Brazilian phone mask. See that for the mask to be applied, inform the index and which character you want to add, and that's it, now you have an input mask!
function App() {
const inputRef = useRef(null)
return (
<InputMask
ref={inputRef}
maxLength={19}
placeholder='+55 (12) 98765-4321'
cb={(event) => console.log(event)}
masks={[
{ index: 0, character: '+' },
{ index: 3, character: ' ' },
{ index: 4, character: '(' },
{ index: 7, character: ')' },
{ index: 8, character: ' ' },
{ index: 14, character: '-' },
]}
/>
)
}
export default App
Prop | Required | Type | Description |
---|---|---|---|
ref | true | HTMLInputElement | Ref of the input that gives freedom to manipulate the input if necessary. |
maxLength | true | Number | Determine the maximum length of the input value. Characters added by the mask are also summed. |
cb | false | Function | Receive event via callback function on input change. |
masks | true | { index: number; character: string; }[] | An array of objects where the index represents the position of the string you want to assign a character to. |
Note:
The character field only accepts characters, and only one per index.