JavaScript library for formatting input text content when you are typing
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Complete API reference for using Cleave.js React component with controlled and uncontrolled patterns, event handling, and ref access to instance methods.
The Cleave React component provides a wrapper around the vanilla Cleave.js functionality with React-specific props and event handling.
/**
* Cleave React Component
* Supports both controlled and uncontrolled component patterns
*/
interface CleaveReactComponent {
// All Cleave.js configuration options
creditCard?: boolean;
creditCardStrictMode?: boolean;
onCreditCardTypeChanged?: (type: string) => void;
phone?: boolean;
phoneRegionCode?: string;
date?: boolean;
datePattern?: string[];
dateMin?: string;
dateMax?: string;
time?: boolean;
timePattern?: string[];
timeFormat?: string;
numeral?: boolean;
numeralDecimalMark?: string;
numeralIntegerScale?: number;
numeralDecimalScale?: number;
numeralThousandsGroupStyle?: 'thousand' | 'lakh' | 'wan' | 'none';
numeralPositiveOnly?: boolean;
stripLeadingZeroes?: boolean;
signBeforePrefix?: boolean;
tailPrefix?: boolean;
blocks?: number[];
delimiter?: string;
delimiters?: string[];
delimiterLazyShow?: boolean;
prefix?: string;
noImmediatePrefix?: boolean;
rawValueTrimPrefix?: boolean;
copyDelimiter?: boolean;
numericOnly?: boolean;
uppercase?: boolean;
lowercase?: boolean;
swapHiddenInput?: boolean;
initValue?: string;
// React-specific props
value?: string; // Controlled component value
onChange?: (event: React.ChangeEvent<HTMLInputElement>) => void;
onFocus?: (event: React.FocusEvent<HTMLInputElement>) => void;
onBlur?: (event: React.FocusEvent<HTMLInputElement>) => void;
onKeyDown?: (event: React.KeyboardEvent<HTMLInputElement>) => void;
onInit?: (cleave: CleaveInstance) => void; // Initialization callback with instance
htmlRef?: (ref: HTMLInputElement) => void; // Ref callback for input element
options?: CleaveOptions; // Alternative way to pass cleave options
// Standard HTML input props
[key: string]: any;
}
interface CleaveInstance {
setRawValue(value: string): void;
getRawValue(): string;
getFormattedValue(): string;
getISOFormatDate(): string;
getISOFormatTime(): string;
element: HTMLInputElement | null;
properties: object;
// React component methods
setState(state: object): void;
state: { value: string; cursorPosition: number };
}Usage Examples:
import React, { useState, useRef } from 'react';
import Cleave from 'cleave.js/react';
// Controlled component
function CreditCardForm() {
const [cardNumber, setCardNumber] = useState('');
const [cardType, setCardType] = useState('');
return (
<Cleave
value={cardNumber}
creditCard={true}
onChange={(e) => {
setCardNumber(e.target.value);
console.log('Raw value:', e.target.rawValue);
}}
onCreditCardTypeChanged={(type) => {
setCardType(type);
}}
placeholder="Enter credit card number"
/>
);
}
// Uncontrolled component with ref
function PhoneForm() {
const cleaveRef = useRef(null);
const handleSubmit = () => {
if (cleaveRef.current) {
console.log('Raw phone:', cleaveRef.current.getRawValue());
console.log('Formatted:', cleaveRef.current.getFormattedValue());
}
};
return (
<div>
<Cleave
phone={true}
phoneRegionCode="US"
htmlRef={(ref) => { cleaveRef.current = ref?.cleave; }}
onInit={(cleave) => {
cleaveRef.current = cleave;
}}
/>
<button onClick={handleSubmit}>Submit</button>
</div>
);
}Using Cleave as a controlled React component with state management.
/**
* Controlled component pattern with value prop
*/
interface ControlledCleaveProps {
value: string; // Required for controlled component
onChange: (event: React.ChangeEvent<HTMLInputElement>) => void; // Required handler
}Usage Examples:
import React, { useState } from 'react';
import Cleave from 'cleave.js/react';
function ControlledExample() {
const [amount, setAmount] = useState('');
const [date, setDate] = useState('');
return (
<form>
{/* Currency input */}
<Cleave
value={amount}
numeral={true}
numeralDecimalScale={2}
prefix="$"
onChange={(e) => {
setAmount(e.target.value);
console.log('Raw amount:', e.target.rawValue);
}}
placeholder="Enter amount"
/>
{/* Date input */}
<Cleave
value={date}
date={true}
datePattern={['m', 'd', 'Y']}
onChange={(e) => {
setDate(e.target.value);
console.log('ISO date:', e.target.cleave?.getISOFormatDate());
}}
placeholder="MM/DD/YYYY"
/>
</form>
);
}Using Cleave as an uncontrolled component with refs for value access.
/**
* Uncontrolled component pattern using refs
*/
interface UncontrolledCleaveProps {
onInit?: (cleave: CleaveInstance) => void; // Access to cleave instance
htmlRef?: (ref: HTMLInputElement) => void; // Access to input element
}Usage Examples:
import React, { useRef } from 'react';
import Cleave from 'cleave.js/react';
function UncontrolledExample() {
const cleaveInstanceRef = useRef(null);
const inputElementRef = useRef(null);
const handleGetValues = () => {
if (cleaveInstanceRef.current) {
const raw = cleaveInstanceRef.current.getRawValue();
const formatted = cleaveInstanceRef.current.getFormattedValue();
console.log({ raw, formatted });
}
};
const handleSetValue = () => {
if (cleaveInstanceRef.current) {
cleaveInstanceRef.current.setRawValue('4111111111111111');
}
};
return (
<div>
<Cleave
creditCard={true}
onInit={(cleave) => {
cleaveInstanceRef.current = cleave;
}}
htmlRef={(ref) => {
inputElementRef.current = ref;
}}
placeholder="Credit card number"
/>
<button onClick={handleGetValues}>Get Values</button>
<button onClick={handleSetValue}>Set Test Value</button>
</div>
);
}React-specific event handling with enhanced event objects.
/**
* Enhanced React change event with cleave-specific properties
*/
interface CleaveReactChangeEvent extends React.ChangeEvent<HTMLInputElement> {
target: HTMLInputElement & {
rawValue: string; // Raw unformatted value
value: string; // Formatted display value
name: string; // Input name attribute
};
}
/**
* Event handler props
*/
interface CleaveEventProps {
onChange?: (event: CleaveReactChangeEvent) => void;
onFocus?: (event: React.FocusEvent<HTMLInputElement>) => void;
onBlur?: (event: React.FocusEvent<HTMLInputElement>) => void;
onKeyDown?: (event: React.KeyboardEvent<HTMLInputElement>) => void;
onInit?: (cleave: CleaveInstance) => void;
}Usage Examples:
import React, { useState } from 'react';
import Cleave from 'cleave.js/react';
function EventHandlingExample() {
const [formData, setFormData] = useState({
phone: '',
amount: '',
cardType: ''
});
return (
<form>
<Cleave
name="phone"
phone={true}
phoneRegionCode="US"
onChange={(e) => {
setFormData(prev => ({
...prev,
phone: e.target.rawValue
}));
}}
onFocus={(e) => {
console.log('Phone input focused');
}}
onBlur={(e) => {
console.log('Phone input blurred:', e.target.value);
}}
/>
<Cleave
name="amount"
numeral={true}
prefix="$"
onChange={(e) => {
setFormData(prev => ({
...prev,
amount: e.target.rawValue
}));
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
console.log('Enter pressed on amount field');
}
}}
/>
<Cleave
name="creditCard"
creditCard={true}
onCreditCardTypeChanged={(type) => {
setFormData(prev => ({
...prev,
cardType: type
}));
}}
onInit={(cleave) => {
console.log('Credit card input initialized:', cleave);
}}
/>
</form>
);
}Changing Cleave configuration based on component state or props.
Usage Examples:
import React, { useState } from 'react';
import Cleave from 'cleave.js/react';
function DynamicConfigExample() {
const [country, setCountry] = useState('US');
const [inputType, setInputType] = useState('phone');
const getPhoneConfig = () => ({
phone: true,
phoneRegionCode: country
});
const getDateConfig = () => ({
date: true,
datePattern: ['m', 'd', 'Y']
});
return (
<div>
<select onChange={(e) => setCountry(e.target.value)}>
<option value="US">United States</option>
<option value="UK">United Kingdom</option>
<option value="AU">Australia</option>
</select>
<select onChange={(e) => setInputType(e.target.value)}>
<option value="phone">Phone</option>
<option value="date">Date</option>
</select>
<Cleave
key={`${inputType}-${country}`} // Force re-render on config change
{...(inputType === 'phone' ? getPhoneConfig() : getDateConfig())}
placeholder={inputType === 'phone' ? 'Phone number' : 'Date'}
/>
</div>
);
}Integration with form libraries and validation.
Usage Examples:
import React from 'react';
import Cleave from 'cleave.js/react';
import { useForm, Controller } from 'react-hook-form';
function FormIntegrationExample() {
const { control, handleSubmit, watch } = useForm();
const onSubmit = (data) => {
console.log('Form data:', data);
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<Controller
name="creditCard"
control={control}
render={({ field: { onChange, value, name } }) => (
<Cleave
name={name}
value={value || ''}
creditCard={true}
onChange={(e) => {
onChange(e.target.rawValue); // Store raw value in form
}}
placeholder="Credit card number"
/>
)}
/>
<Controller
name="phone"
control={control}
render={({ field: { onChange, value, name } }) => (
<Cleave
name={name}
value={value || ''}
phone={true}
phoneRegionCode="US"
onChange={(e) => {
onChange(e.target.rawValue);
}}
placeholder="Phone number"
/>
)}
/>
<button type="submit">Submit</button>
</form>
);
}Type definitions for TypeScript projects.
/**
* TypeScript interfaces for type safety
*/
import { ComponentProps } from 'react';
interface CleaveProps extends Omit<ComponentProps<'input'>, 'onChange' | 'onFocus' | 'onBlur' | 'onKeyDown'> {
// Cleave-specific props
creditCard?: boolean;
phone?: boolean;
date?: boolean;
time?: boolean;
numeral?: boolean;
// ... other cleave options
// React-specific props with proper typing
value?: string;
onChange?: (event: CleaveReactChangeEvent) => void;
onFocus?: (event: React.FocusEvent<HTMLInputElement>) => void;
onBlur?: (event: React.FocusEvent<HTMLInputElement>) => void;
onKeyDown?: (event: React.KeyboardEvent<HTMLInputElement>) => void;
onInit?: (cleave: CleaveInstance) => void;
htmlRef?: (ref: HTMLInputElement | null) => void;
}
// Usage in TypeScript
const MyComponent: React.FC = () => {
const [value, setValue] = useState<string>('');
const handleChange = (e: CleaveReactChangeEvent) => {
setValue(e.target.rawValue);
};
return (
<Cleave
value={value}
creditCard={true}
onChange={handleChange}
/>
);
};Install with Tessl CLI
npx tessl i tessl/npm-cleave-js