/@maskito/react is a light-weighted library to use Maskito in an React-way.
To get the most out of this guide, you should review the topic "Core Concepts" first.
Install libraries
npm install @maskito/{core,react}
and use Maskito
See the result of above code example in action:
Maskito core is developed as framework-agnostic library. It does not depend on any JS-framework's peculiarities. It uses only native browser API. That is why we strongly recommends use native onInput instead of React-specific onChange event handler. Do not worry, both events works similarly! Read more about it in the official React documentation.
onChange is supported by Maskito too but usage of onInput handler is a more robust solution!
import {useState} from 'react';
import {useMaskito} from '@maskito/react';
const digitsOnlyMask: MaskitoOptions = {
mask: /^\d+$/,
};
function App() {
const inputRef = useMaskito({options: digitsOnlyMask});
const [value, setValue] = useState('');
// Use `onInput` handler to build controlled input
return (
<input
ref={inputRef}
value={value}
onInput={(e) => setValue(e.currentTarget.value)}
/>
);
}
Do you need to use multiple hooks that return refs which both should be attached to the masked textfield?
Use ref callback !
import {useMaskito} from '@maskito/react';
const options: MaskitoOptions = {
mask: /^\d+$/,
};
function App() {
const anyExternalRef = useRef(null);
const maskitoRef = useMaskito({options});
return (
<input
ref={(node) => {
maskitoRef(node);
anyExternalRef.current = node;
}}
/>
);
}
Pass a predicate to elementPredicate to find input element for you, if you do not have a direct access to it. For example, you use component from some UI Kit library.
host.querySelector('input,textarea') so that might be sufficient. Use custom predicate if you need custom logic. There is not silver bullet how to integrate Maskito with any library for form-building. Explore all examples above – the provided knowledge about element predicate, ref merging and OnInput event will help you a lot to achieve it.
This example demonstrates how to use Maskito with popular library react-hook-form .
// Best Practice ✅
useMaskito({
options: maskitoOptions,
elementPredicate: predicate,
});
// Anti-Pattern ❌
useMaskito({
options: {mask: /^.*$/},
elementPredicate: () => e.querySelector('input#my-input'),
});