React Input Mask
Input mask
React input masks allow you to regulate the format of data entered. You can enhance data entry accuracy by implementing react input masks for fields with consistent formatting requirements. This ensures that users input data correctly, such as accurately formatted phone numbers in a designated phone number field.
Usage#
While CoreUI for React does not currently include a 'mask' feature, it can be enhanced by leveraging existing libraries like react-imask
to extend the functionality of our components.
To enable the extension of the <CFormInput />
component, please ensure that you have installed react-imask
first.
npm install react-imask
or
yarn add react-imask
Once you have installed react-imask, you can proceed to create a custom component with a mask.
import { IMaskMixin } from 'react-imask'
const CFormInputWithMask = IMaskMixin(({ inputRef, ...props }) => ( <CFormInput {...props} ref={inputRef} // bind internal input />))
Here is an example of a date mask for reference.
const CFormInputWithMask = IMaskMixin(({ inputRef, ...props }) => ( <CFormInput {...props} ref={inputRef} />))return ( <CFormInputWithMask mask={Date} min={new Date(1990, 0, 1)} max={new Date(2020, 0, 1)} lazy={false} />)
Example masks#
Please take a moment to review some example masks you can use for reference. These examples serve as helpful templates for implementing input masks and can assist you in effectively controlling data entry formats.
Phone#
This example react input mask for a phone number follows the format commonly used in North America. It consists of three groups of numbers: the area code enclosed in parentheses, followed by a space, and then the seven-digit phone number separated by a hyphen.
const CFormInputWithMask = IMaskMixin(({ inputRef, ...props }) => ( <CFormInput {...props} ref={inputRef} />))return <CFormInputWithMask mask="+{1}(000)000-00-00" />
Credit Card#
The provided code snippet demonstrates an implementation of an react input mask for a credit card number using the IMask library in JavaScript. The mask is set to "0000 0000 0000 0000", indicating that the input should consist of a 16-digit credit card number with spaces separating every four digits. The component renders an input field with the specified mask, allowing users to enter credit card numbers in the desired format.
const CFormInputWithMask = IMaskMixin(({ inputRef, ...props }) => ( <CFormInput {...props} ref={inputRef} />))return <CFormInputWithMask mask="0000 0000 0000 0000" />
For more information on how to use the input mask, you can refer to the following resource: https://imask.js.org/