react-imask is a React-specific plugin for the robust imask.js library, providing components and hooks to easily integrate input masking into React applications. The current stable version is 7.6.1, with minor releases occurring every few weeks, indicating active development. It differentiates itself by offering dedicated React components like IMaskInput, a Higher-Order Component IMaskMixin for extending existing inputs, and the useIMask hook for functional components. It emphasizes onAccept as the primary event handler for masked value changes, explicitly warning against the common React pattern of using onChange for this purpose. The core imask.js library underpins its powerful masking capabilities, including Number, Pattern, Enum, and Dynamic masks, alongside features like autofix, repeat blocks, and improved IME support.
npm install react-imaskVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates the basic usage of the IMaskInput component, showing how to apply a Number mask, access internal refs, and correctly handle changes using the onAccept prop instead of onChange.
Replace `onChange={(e) => ...}` with `onAccept={(value, mask) => ...}`. The `value` argument to `onAccept` depends on the `unmask` prop (e.g., `unmaskedValue` if `unmask={true}`).Check your `styled-components` version. If `V4`, pass `innerRef={inputRef}` to your styled component within the `IMaskMixin`. If `V5+`, use `ref={inputRef}`.Review any logic that relied on `onAccept` firing unconditionally on component mount or initialization, especially related to form validation state. Adjust logic to explicitly check for initial value changes if needed, or rely on subsequent `onAccept` calls for user interaction.
Ensure your project uses a modern Node.js version (LTS recommended) and a bundler (e.g., Webpack 5, Rollup, Vite) that fully supports package `exports` and mixed module types. If encountering module resolution errors, explicitly configure your bundler to resolve `react-imask` as ESM or CJS if necessary.
Ensure the ref is properly assigned to the `IMaskInput` component or returned by `useIMask`, and that you access `ref.current?.maskRef` only after the component has rendered and `ref.current` is not null.
If using the `value` prop, always provide an `onAccept` handler to keep the component controlled. If you intend for the input to manage its own state after initial render, use the `defaultValue` prop instead of `value`.
For `useIMask`, use the `setValue` function returned by the hook. For `IMaskInput`, update the `value` prop passed to the component directly, allowing React to manage updates correctly through the mask.