### Start Local Development Server
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/README.md
Starts a local development server for live preview. Changes are reflected without server restart.
```bash
yarn start
```
--------------------------------
### Install react-number-format
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Install the library using npm or yarn.
```bash
npm install react-number-format
# or
yarn add react-number-format
```
--------------------------------
### Install Dependencies
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/README.md
Installs project dependencies using Yarn.
```bash
yarn
```
--------------------------------
### Install React Number Format with yarn
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/intro.md
Use this command to add the react-number-format package to your project via yarn.
```bash
yarn add react-number-format
```
--------------------------------
### Install React Number Format with npm
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/intro.md
Use this command to add the react-number-format package to your project via npm.
```bash
npm install react-number-format
```
--------------------------------
### Custom Currency Format with Intl.NumberFormat
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Create a custom currency formatter using `NumberFormatBase` and the browser's `Intl.NumberFormat` API. This example formats numbers into USD currency.
```jsx
import { NumberFormatBase } from 'react-number-format';
// Custom currency format using Intl.NumberFormat
function IntlCurrencyFormat(props) {
const format = (numStr) => {
if (numStr === '') return '';
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
maximumFractionDigits: 0,
}).format(numStr);
};
return ;
}
// User types: 1234 -> Displays: $1,234
```
--------------------------------
### Basic Intl.NumberFormat Currency Formatting
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/customization.md
Implement currency formatting using `Intl.NumberFormat` for a basic use case without decimals or negative number support. This example demonstrates how to integrate `Intl.NumberFormat` with `NumberFormatBase`.
```javascript
import { NumberFormatBase } from 'react-number-format';
function MyCustomNumberFormat(props) {
const format = (numStr) => {
if (numStr === '') return '';
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
maximumFractionDigits: 0,
}).format(numStr);
};
return ;
}
```
--------------------------------
### Card Expiry Field with usePatternFormat
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/customization.md
This example demonstrates creating a card expiry field by extending NumberFormatBase with the usePatternFormat hook for predefined pattern application.
```javascript
function CardExpiry(props) {
/**
* usePatternFormat, returns all the props required for NumberFormatBase
* which we can extend in between
*/
const { format, ...rest } = usePatternFormat({ ...props, format: '##/##' });
const _format = (val) => {
let month = val.substring(0, 2);
const year = val.substring(2, 4);
if (month.length === 1 && month[0] > 1) {
month = `0${month[0]}`;
} else if (month.length === 2) {
// set the lower and upper boundary
if (Number(month) === 0) {
month = `01`;
} else if (Number(month) > 12) {
month = '12';
}
}
return format(`${month}${year}`);
};
return ;
}
```
--------------------------------
### Card Expiry Input Formatting
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Implement a custom input formatter for card expiry dates using `NumberFormatBase`. This example handles month and year formatting, including validation for month input.
```jsx
import { NumberFormatBase } from 'react-number-format';
// Card expiry field with validation
function CardExpiry(props) {
const format = (val) => {
if (val === '') return '';
let month = val.substring(0, 2);
const year = val.substring(2, 4);
if (month.length === 1 && month[0] > 1) {
month = `0${month[0]}`;
} else if (month.length === 2) {
if (Number(month) === 0) month = '01';
else if (Number(month) > 12) month = '12';
}
return `${month}/${year}`;
};
return ;
}
// User types: 1223 -> Displays: 12/23
// User types: 9 -> Displays: 09/
```
--------------------------------
### Getting Input Reference
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Access the input element's reference using the getInputRef prop, allowing direct manipulation or focus control.
```jsx
import { NumericFormat, PatternFormat } from 'react-number-format';
import { TextField } from '@mui/material';
// Getting input reference
function InputRefExample() {
const inputRef = useRef(null);
return (
console.log('Focused:', inputRef.current)}
/>
);
}
```
--------------------------------
### Getting input reference with getInputRef
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/props.md
The `getInputRef` prop allows you to obtain a reference to the input element, span, or custom input component.
```javascript
import { NumericFormat } from 'react-number-format';
import { useRef } from 'react';
export default function App() {
let ref = useRef();
return ;
}
```
--------------------------------
### getInputRef Prop
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/props.md
A method to get a reference to the input element, span (depending on `displayType`), or the `customInput`'s reference.
```APIDOC
## getInputRef Prop
### Description
Method to get reference of input, span (based on displayType prop) or the customInput's reference.
### Type
`elm => void`
### Default
`null`
### Usage Example
```javascript
import { NumericFormat } from 'react-number-format';
import { useRef } from 'react';
export default function App() {
let ref = useRef();
return ;
}
```
```
--------------------------------
### Deploy Website (SSH)
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/README.md
Builds and deploys the website using SSH. Assumes SSH is configured.
```bash
USE_SSH=true yarn deploy
```
--------------------------------
### Build Static Website
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/README.md
Generates static content for hosting on any static content service.
```bash
yarn build
```
--------------------------------
### Deploy Website (No SSH)
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/README.md
Builds and deploys the website without SSH. Requires specifying GitHub username.
```bash
GIT_USER= yarn deploy
```
--------------------------------
### Development: Run tests
Source: https://github.com/s-yadav/react-number-format/blob/master/README.md
Execute test cases using yarn to verify changes.
```bash
yarn test
```
--------------------------------
### PatternFormat for Credit Card Input
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Demonstrates credit card formatting using PatternFormat with a custom pattern and mask. The value prop can pre-fill the input.
```jsx
import { PatternFormat } from 'react-number-format';
// Credit card formatting with custom pattern character
function CreditCardInput() {
return (
);
}
// Displays: 4111 1111 1111 1111
```
--------------------------------
### Unformat Input Value
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/numeric_format.md
The `removeNumericFormat` utility function is used to get the raw number string from a formatted input value. It's typically used in custom formatting scenarios.
```javascript
function removeNumericFormat(inputValue: string, changeMeta: ChangeMeta, props: NumericFormatProps) => string;
```
--------------------------------
### Handling Empty Input with allowEmptyFormatting
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Demonstrates how to use the allowEmptyFormatting prop with useNumericFormat to control the display of prefixes and suffixes when the input is empty.
```jsx
function NumericWithEmptyFormatting(props) {
const { prefix = '', suffix = '', allowEmptyFormatting } = props;
const { format, ...numberFormatBaseProps } = useNumericFormat(props);
const _format = (numStr, props) => {
const formattedValue = format(numStr, props);
return allowEmptyFormatting && formattedValue === '' ? prefix + suffix : formattedValue;
};
return ;
}
```
--------------------------------
### Define Number Format Pattern
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/pattern_format.md
Use the 'format' prop with '#' as the placeholder for numbers to define the input pattern.
```javascript
import { PatternFormat } from 'react-number-format';
;
```
--------------------------------
### Import NumericFormat or PatternFormat
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/migration.md
Import NumericFormat for number-based formatting or PatternFormat for pattern-based formatting. This replaces the older NumberFormat import.
```javascript
import NumberFormat from 'react-number-format';
```
```javascript
import { NumericFormat } from 'react-number-format';
```
```javascript
\nor
import { PatternFormat } from 'react-number-format';
```
--------------------------------
### Add Prefix to Input
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/numeric_format.md
Use the `prefix` prop to prepend a character or string before the input value. Useful for currency symbols or units.
```javascript
import { NumericFormat } from 'react-number-format';
;
```
--------------------------------
### Enable Empty Formatting with PatternFormat
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/pattern_format.md
Set allowEmptyFormatting to true to apply formatting to empty values (null, undefined, or '').
```javascript
import { PatternFormat } from 'react-number-format';
;
```
--------------------------------
### NumericFormat for Currency Input
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Use NumericFormat for currency formatting with a prefix, thousands separator, and fixed decimal places. The onValueChange callback provides formatted and raw values.
```jsx
import { NumericFormat } from 'react-number-format';
// Currency formatting with prefix, thousands separator, and decimal control
function CurrencyInput() {
const [value, setValue] = useState('');
return (
{
// values = { formattedValue: '$1,234.56', value: '1234.56', floatValue: 1234.56 }
// sourceInfo = { event: SyntheticEvent, source: 'event' | 'prop' }
setValue(values.value);
}}
/>
);
}
// User types: 1234.5 -> Displays: $1,234.50
// values.formattedValue = '$1,234.50'
// values.value = '1234.50'
// values.floatValue = 1234.5
```
--------------------------------
### Import NumberFormatBase for Custom Formatting
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/migration.md
Import NumberFormatBase when using custom formatting functions. This module handles custom formatter-based formatting.
```javascript
import { NumberFormatBase} from "react-number-format";
```
--------------------------------
### Setting the defaultValue prop
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/props.md
Use the `defaultValue` prop to set an initial value for the input field when the `value` prop is not provided.
```javascript
import { NumericFormat } from 'react-number-format';
;
```
--------------------------------
### Utility Functions
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/numeric_format.md
Exposes utility functions for number formatting and manipulation.
```APIDOC
## Other Exports
### numericFormatter
- **Signature**: `(numString: string, props: NumericFormatProps) => string`
- **Description**: Formats a number string according to the provided props. Useful for formatting numbers before displaying them or passing them as values.
- **Parameters**:
- `numString` (string): The non-formatted number string.
- `props` (NumericFormatProps): The formatting props applicable to `NumericFormat`.
- **Returns**: `string` - The formatted number string.
### removeNumericFormat
- **Signature**: `(inputValue: string, changeMeta: ChangeMeta, props: NumericFormatProps) => string`
- **Description**: Removes numeric formatting from an input value. Primarily for advanced customization scenarios. For customization, using the `useNumericFormat` hook is recommended.
- **Parameters**:
- `inputValue` (string): The formatted value, including any characters typed by the user.
- `changeMeta` (ChangeMeta): Information about the change, including `from`, `to`, and `lastValue`.
- `from`: `{start: number, end: number}`
- `to`: `{start: number, end: number}`
- `lastValue`: `string`
- `props` (NumericFormatProps): All applicable `NumericFormat` props.
- **Returns**: `string` - The number string in its unformatted state.
```
--------------------------------
### Custom Persian Numeral Formatting with useNumericFormat Hook
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Implements Persian numeral support by extending useNumericFormat. It customizes formatting, removal of formatting, and character comparison logic.
```jsx
function PersianNumeralFormat(props) {
const persianNumeral = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
const { format, removeFormatting, isCharacterSame, ...rest } = useNumericFormat(props);
const _format = (val) => {
const _val = format(val);
return _val.replace(/\d/g, ($1) => persianNumeral[Number($1)]);
};
const _removeFormatting = (val) => {
const _val = val.replace(new RegExp(persianNumeral.join('|'), 'g'), ($1) =>
persianNumeral.indexOf($1)
);
return removeFormatting(_val);
};
const _isCharacterSame = (compareMeta) => {
const isCharSame = isCharacterSame(compareMeta);
const { formattedValue, currentValue, formattedValueIndex, currentValueIndex } = compareMeta;
const curChar = currentValue[currentValueIndex];
const newChar = formattedValue[formattedValueIndex];
const curPersianChar = persianNumeral[Number(curChar)] ?? curChar;
const newPersianChar = persianNumeral[Number(newChar)] ?? newChar;
return isCharSame || curPersianChar === newPersianChar;
};
return (
);
}
```
--------------------------------
### customInput Prop
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/props.md
Allows supporting custom input components with number formatting. The `customInput` prop expects a reference to a component, not a render prop.
```APIDOC
## customInput Prop
### Description
This prop allows supporting custom input components with number format.
### Type
`React.Component`
### Default
`null`
### Usage Example
```javascript
import { NumericFormat } from 'react-number-format';
import { TextField } from '@mui/material';
;
```
### Note
`customInput` expects a reference of a component (not a render prop). If you pass an inline component like this `} />`, it will not work.
```
--------------------------------
### Import PatternFormat Component (ES6)
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/intro.md
Import the PatternFormat component for custom pattern-based input formatting in your ES6 React application.
```javascript
import { PatternFormat } from 'react-number-format';
```
--------------------------------
### Card Expiry Formatting with usePatternFormat Hook
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Customizes card expiry input using the usePatternFormat hook to enforce a '##/##' format and includes logic for validating month input.
```jsx
import { NumberFormatBase, useNumericFormat, usePatternFormat } from 'react-number-format';
// Card expiry with pattern format hooks
function CardExpiryWithHook(props) {
const { format, ...rest } = usePatternFormat({ ...props, format: '##/##' });
const _format = (val) => {
let month = val.substring(0, 2);
const year = val.substring(2, 4);
if (month.length === 1 && month[0] > 1) {
month = `0${month[0]}`;
} else if (month.length === 2) {
if (Number(month) === 0) month = '01';
else if (Number(month) > 12) month = '12';
}
return format(`${month}${year}`);
};
return ;
}
```
--------------------------------
### Using Custom Input Component (Material-UI)
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Integrate NumericFormat with custom input components like Material-UI's TextField by passing the component to the customInput prop.
```jsx
import { NumericFormat, PatternFormat } from 'react-number-format';
import { TextField } from '@mui/material';
// Using custom input component (Material-UI TextField)
function CustomInputExample() {
return (
);
}
```
--------------------------------
### Implement Custom Numeral Formatting in React
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/customization.md
Use this component to format numbers with custom numeral systems, such as Persian digits. It requires a custom format function and a way to handle character comparisons.
```javascript
const persianNumeral = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
function CustomNumeralNumericFormat(props) {
const { format, removeFormatting, isCharacterSame, ...rest } = useNumericFormat(props);
const _format = (val) => {
const _val = format(val);
return _val.replace(/\d/g, ($1) => persianNumeral[Number($1)]);
};
const _removeFormatting = (val) => {
const _val = val.replace(new RegExp(persianNumeral.join('|'), 'g'), ($1) =>
persianNumeral.indexOf($1),
);
return removeFormatting(_val);
};
const _isCharacterSame = (compareMeta) => {
const isCharSame = isCharacterSame(compareMeta);
const { formattedValue, currentValue, formattedValueIndex, currentValueIndex } = compareMeta;
const curChar = currentValue[currentValueIndex];
const newChar = formattedValue[formattedValueIndex];
const curPersianChar = persianNumeral[Number(curChar)] ?? curChar;
const newPersianChar = persianNumeral[Number(newChar)] ?? newChar;
return isCharSame || curPersianChar === newPersianChar;
};
return (
);
}
```
--------------------------------
### Configure Thousands Grouping Style
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/numeric_format.md
The `thousandsGroupStyle` prop defines how numbers are grouped for thousands. Supported styles include 'thousand' (e.g., 123,456,789), 'lakh' (e.g., 12,34,56,789), and 'wan' (e.g., 1,2345,6789).
```javascript
import { NumericFormat } from 'react-number-format';
;
```
--------------------------------
### Format Strings with Pattern Formatter
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Utilize `patternFormatter` to format strings according to a specified pattern. This is useful for phone numbers, credit cards, and other structured inputs.
```jsx
// Pattern formatting for phone numbers
const formattedPhone = patternFormatter('1234567890', {
format: '+1 (###) ###-####',
});
console.log(formattedPhone); // "+1 (123) 456-7890"
```
```jsx
// Pattern formatting for credit cards
const formattedCard = patternFormatter('4111111111111111', {
format: '#### #### #### ####',
});
console.log(formattedCard); // "4111 1111 1111 1111"
```
--------------------------------
### Input Validation with isAllowed Prop
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Implement custom input validation using the isAllowed prop, which receives value objects and should return a boolean to determine if the input is permitted.
```jsx
import { NumericFormat, PatternFormat } from 'react-number-format';
import { TextField } from '@mui/material';
// Input validation with isAllowed
function ValidatedInput() {
const MAX_LIMIT = 10000;
return (
{
const { floatValue } = values;
return floatValue === undefined || floatValue <= MAX_LIMIT;
}}
/>
);
}
// Prevents user from entering values > $10,000
```
--------------------------------
### Setting the value prop
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/props.md
The `value` prop accepts a number or a string representation of the number for the input field. If the value is a string and formatting is applied, consider using `valueIsNumericString`.
```javascript
import { NumericFormat } from 'react-number-format';
;
```
--------------------------------
### patternFormatter Utility
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/pattern_format.md
Details on the patternFormatter utility function for custom formatting.
```APIDOC
## patternFormatter Utility
### `patternFormatter(numString: string, props: PatternFormatProps) => string`
This utility can be used to format a number string before passing it down as a value or for general rendering purposes.
**Parameters**
1. `numString` (non-formatted number string)
2. `props` (the format props applicable on numeric format)
**Return**
`formattedString`: The formatted number string.
```
--------------------------------
### usePatternFormat Hook
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/pattern_format.md
The core hook for number formatting logic, providing props that can be passed to NumberFormatBase for customization.
```APIDOC
## usePatternFormat
### Description
This hook encapsulates the primary logic for number formatting within `react-number-format`. It returns a set of props that are essential for the `NumberFormatBase` component. For advanced customization, you can patch the methods returned by this hook before passing them to `NumberFormatBase`.
### Method
`usePatternFormat(props: PatternFormatProps) => NumberFormatBaseProps`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
1. **props** (object) - Required - All the formatting-related props for the `PatternFormat` component.
### Request Example
```javascript
import { usePatternFormat } from 'react-number-format';
const MyCustomInput = (props) => {
const numberFormatProps = usePatternFormat(props);
// You can patch methods here if needed
// const patchedNumberFormatProps = patchMethods(numberFormatProps);
return ;
};
```
### Response
#### Success Response (200)
- **NumberFormatBaseProps** (object) - An object containing all the necessary props to be passed to the `NumberFormatBase` component, including event handlers and formatting logic.
#### Response Example
```json
{
"onValueChange": "function",
"onFocus": "function",
"onBlur": "function",
"format": "string",
"mask": "string",
"value": "string"
}
```
```
--------------------------------
### allowedDecimalSeparators Prop
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/numeric_format.md
Specifies an array of characters that, when pressed, will be recognized as decimal separators. If not provided, the default decimal separator and '.' are used.
```APIDOC
## allowedDecimalSeparators Prop
### Description
Characters which when pressed result in a decimal separator. When missing, decimal separator and '.' are used.
### Type
`Array`
### Default
`undefined`
### Usage Example
```js
import { NumericFormat } from 'react-number-format';
;
```
```
--------------------------------
### Format Number String with PatternFormatter Utility
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/pattern_format.md
The patternFormatter utility can be used directly to format a number string with specified props before rendering.
```javascript
patternFormatter(numString, props)
```
--------------------------------
### Import NumericFormat Component (ES6)
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/intro.md
Import the NumericFormat component for handling numeric input formatting in your ES6 React application.
```javascript
import { NumericFormat } from 'react-number-format';
```
--------------------------------
### SourceInfo Object Structure
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/quirks.md
The 'sourceInfo' object indicates the origin of a change, differentiating between user 'event' and 'prop' updates. This helps in managing controlled and uncontrolled component behaviors.
```js
{
event: SyntheticEvent; // This is the event object of type Synthetic Event
source: 'event' | 'prop'; // Source information indicating whether it is due to an event or a prop change
}
```
--------------------------------
### Enable Fixed Decimal Scale
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/numeric_format.md
Set `fixedDecimalScale` to true to add trailing zeros after the decimal separator to match the `decimalScale`. Requires `decimalScale` to be set.
```javascript
import { NumericFormat } from 'react-number-format';
;
```
--------------------------------
### Enable AllowEmptyFormatting for NumericFormat in React
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/customization.md
Achieve the allowEmptyFormatting behavior for NumericFormat by creating a custom component. This ensures that an empty formatted value results in the prefix and suffix being displayed.
```javascript
function CustomNumberFormat(props) {
const { prefix = '', suffix = '', allowEmptyFormatting } = props;
const { format, ...numberFormatBaseProps } = useNumericFormat(props);
const _format = (numStr, props) => {
const formattedValue = format(numStr, props);
return allowEmptyFormatting && formattedValue === '' ? prefix + suffix : formattedValue;
};
return ;
}
```
--------------------------------
### Create Custom Card Expiry Field
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/customization.md
This snippet shows how to create a custom card expiry input field using NumberFormatBase with custom formatting and keydown event handling.
```javascript
import { NumberFormatBase } from 'react-number-format';
function CardExpiry(props) {
const format = (val) => {
if (val === '') return '';
let month = val.substring(0, 2);
const year = val.substring(2, 4);
if (month.length === 1 && month[0] > 1) {
month = `0${month[0]}`;
} else if (month.length === 2) {
// set the lower and upper boundary
if (Number(month) === 0) {
month = `01`;
} else if (Number(month) > 12) {
month = '12';
}
}
return `${month}/${year}`;
};
const onKeyDown = (e) => {
const { target } = e;
const { value, selectionStart } = target;
console.log(value);
if (e.key === '/' && value[selectionStart] === '/') {
// if there is number before slash with just one character add 0 prefix
if (value.split('/')[0].length === 1) {
target.value = `0${value}`;
target.selectionStart++;
}
target.selectionStart++;
e.preventDefault();
}
};
return ;
}
```
--------------------------------
### Using customInput with TextField
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/props.md
Pass a reference to a custom input component like Material-UI's TextField to enable custom input functionality. Ensure you pass the component reference, not an inline render prop.
```javascript
import { NumericFormat } from 'react-number-format';
import { TextField } from '@mui/material';
;
```
--------------------------------
### displayType Prop
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/props.md
Determines how the formatted value is displayed. If set to 'input', it renders an input element where formatting occurs as the user types. If set to 'text', it renders the formatted value within a span tag.
```APIDOC
## displayType Prop
### Description
If value is `input`, it renders an input element where formatting happens as you type characters. If value is `text`, it renders formatted text in a span tag.
### Type
`text | input`
### Default
`input`
### Usage Example
```javascript
import { NumericFormat } from 'react-number-format';
;
;
```
```
--------------------------------
### allowLeadingZeros Prop
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/numeric_format.md
Controls whether leading zeros are preserved in the input field. By default, leading zeros are removed on blur. Setting this to `true` allows them.
```APIDOC
## allowLeadingZeros Prop
### Description
This allows enabling or disabling leading zeros in the input field. By default, on blur of an input, leading zeros are removed. To allow leading 0s in the input field, set `allowLeadingZeros` to `true`. This does not, however, control trailing zeros.
### Type
`boolean`
### Default
`false`
### Usage Example
```js
import { NumericFormat } from 'react-number-format';
;
```
```
--------------------------------
### PatternFormat Props
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/pattern_format.md
Details on the specific props for the PatternFormat component.
```APIDOC
## PatternFormat Component Props
### allowEmptyFormatting `boolean`
**default**: `false`
By default, the PatternFormat component does not apply formatting when the value is empty (null, undefined, or ''). Set `allowEmptyFormatting` to `true` to apply formatting on empty values.
**Example:**
```js
import { PatternFormat } from 'react-number-format';
;
```
### format `string`
**default**: `undefined`
Defines the format pattern using the '#' character (or a [`patternChar`](#patternchar-string)). '#' is the placeholder character for numbers.
**Example:**
```js
import { PatternFormat } from 'react-number-format';
;
```
### mask `string | Array`
**default**: `undefined`
Used as a mask character for numeric places until a numeric character is provided for that position. You can provide different mask characters for every numeric position by passing an array of mask characters. **Note**: The length of mask characters should match the number of '#' [patternChar](#patternchar-string).
**Example:**
```js
import { PatternFormat } from 'react-number-format';
;
```
### patternChar `string`
**default**: `#`
This helps define the [`format`](#format-string) pattern character. '#' is the default placeholder for numbers.
**Example:**
```js
import { PatternFormat } from 'react-number-format';
;
```
### Common Props
- [See Common Props](/docs/props)
**Other than these, it accepts all the props which can be given to an input or span based on the `displayType` you selected.**
```
--------------------------------
### Controlled Input with onValueChange Callback
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Shows a controlled input component that uses the onValueChange callback to update its state with formatted value, raw value, and float value. It also logs the source of the change.
```jsx
import { NumericFormat } from 'react-number-format';
function ControlledInput() {
const [values, setValues] = useState({
formattedValue: '',
value: '',
floatValue: undefined,
});
return (
{
// newValues structure:
// {
// formattedValue: '$23,234.56', // Display value with formatting
// value: '23234.56', // Numeric string (no formatting)
// floatValue: 23234.56 // JavaScript number
// }
// sourceInfo structure:
// {
// event: SyntheticEvent, // The DOM event (if triggered by user)
// source: 'event' | 'prop' // What triggered the change
// }
console.log('Source:', sourceInfo.source);
setValues(newValues);
}}
/>
Formatted: {values.formattedValue}
Raw value: {values.value}
Float: {values.floatValue}
);
}
```
--------------------------------
### Add Suffix to Input
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/numeric_format.md
Use the `suffix` prop to append a character or string after the input value. Useful for units or descriptive text.
```javascript
import { NumericFormat } from 'react-number-format';
;
```
--------------------------------
### IBAN Input with Custom Validation and Formatting
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Create an IBAN input field using `NumberFormatBase` that allows alphanumeric characters, formats the input with spaces, and removes formatting for processing. Includes custom character validation and caret boundary logic.
```jsx
import { NumberFormatBase } from 'react-number-format';
// IBAN input field allowing alphanumeric characters
function IBANInput(props) {
return (
value
.replace(/\s+/g, '')
.replace(/([a-z0-9]{4})/gi, '$1 ')
.trim()
.toUpperCase()
}
removeFormatting={(value) => value.replace(/\s+/gi, '')}
isValidInputCharacter={(char) => /^[a-z0-9]$/i.test(char)}
getCaretBoundary={(value) => Array(value.length + 1).fill(true)}
/>
);
}
// User types: de89370400440532013000 -> Displays: DE89 3704 0044 0532 0130 00
```
--------------------------------
### isAllowed Prop
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/props.md
A checker function to validate the input value. If this function returns false, the `onChange` method will not be triggered, and the input value will not change.
```APIDOC
## isAllowed Prop
### Description
A checker function to validate the input value. If this function returns false, the onChange method will not get triggered and the input value will not change.
### Type
`(values) => boolean`
### Default
`undefined`
### Usage Example
```javascript
import { NumericFormat } from 'react-number-format';
const MAX_LIMIT = 1000;
{
const { floatValue } = values;
return floatValue < MAX_LIMIT;
}}
/>;
```
```
--------------------------------
### customInput Prop
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/numeric_format.md
Enables the use of custom input components, such as Material-UI's TextField, allowing for more advanced input styling and functionality.
```APIDOC
## customInput Prop
### Description
This allows supporting custom input components with number format.
### Type
`React.Component`
### Default
`null`
### Usage Example
```js
import { NumericFormat } from 'react-number-format';
import { TextField } from '@mui/material';
;
```
```
--------------------------------
### type
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/props.md
Sets the input type attribute for the number input field.
```APIDOC
## type `string`
### Description
This allows passing the input type attribute value. Supported types include `text`, `tel`, `password`.
### Default
`text`
### Request Example
```javascript
import { NumericFormat } from 'react-number-format';
;
```
```
--------------------------------
### NumericFormat Component Props
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/numeric_format.md
This section details the props available for the NumericFormat component, which allow for customization of number formatting.
```APIDOC
## NumericFormat Component Props
### fixedDecimalScale
- **Type**: `boolean`
- **Default**: `false`
- **Description**: If set to `true`, it adds trailing 0s after `decimalSeparator` to match the given `decimalScale`.
### prefix
- **Type**: `string`
- **Default**: `undefined`
- **Description**: Adds the prefix character before the input value.
### suffix
- **Type**: `string`
- **Default**: `undefined`
- **Description**: Adds the suffix after the input value.
### thousandsGroupStyle
- **Type**: `string`
- **Default**: `,`
- **Description**: Defines the thousand grouping style. Supported types: `thousand` (e.g., 123,456,789), `lakh` (e.g., 12,34,56,789), `wan` (e.g., 1,2345,6789).
### Common Props
- Refer to [Common Props](/docs/props) for additional props.
- The component also accepts all props applicable to an `input` or `span` element based on the `displayType` prop.
```
--------------------------------
### Define Custom Caret Boundary Logic
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/customization.md
Implement a custom function to determine valid caret positions within a formatted string. This is useful when the default caret boundary logic is insufficient for complex formatting.
```javascript
function caretUnknownFormatBoundary(formattedValue) {
const boundaryAry = Array.from({ length: formattedValue.length + 1 }).map(() => true);
for (let i = 0, ln = boundaryAry.length; i < ln; i++) {
// consider caret to be in boundary if it is before or after numeric value
boundaryAry[i] = Boolean(
formattedValue[i].match(/\d/) || formattedValue[i - 1].match(/\d/);
);
}
return boundaryAry;
}
```
--------------------------------
### Format Numbers with Numeric Formatter
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Use `numericFormatter` for standalone number formatting with options for thousand separators, decimal separators, prefixes, and decimal scale. Useful for display or server-side formatting.
```jsx
import { numericFormatter, patternFormatter } from 'react-number-format';
// Format a number for display
const formattedCurrency = numericFormatter('1234567.89', {
thousandSeparator: ',',
decimalSeparator: '.',
prefix: '$',
decimalScale: 2,
fixedDecimalScale: true,
});
console.log(formattedCurrency); // "$1,234,567.89"
```
```jsx
// Format with Indian lakh style grouping
const indianFormat = numericFormatter('12345678', {
thousandSeparator: ',',
thousandsGroupStyle: 'lakh',
});
console.log(indianFormat); // "1,23,45,678"
```
--------------------------------
### Handle Value Changes with onValueChange
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/props.md
The onValueChange handler provides access to input value changes, triggered by prop or user input. It returns a valueObject (formattedValue, value, floatValue) and sourceInfo (event, source) to identify change origins.
```javascript
import { NumericFormat } from 'react-number-format';
{
console.log(values, sourceInfo);
}}
/>;
```
--------------------------------
### PatternFormat for Phone Number Input
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Use PatternFormat with a format string and mask for structured inputs like phone numbers. The valueIsNumericString prop ensures the raw value is a string of digits.
```jsx
import { PatternFormat } from 'react-number-format';
// Phone number formatting
function PhoneInput() {
return (
{
console.log(values.value); // Raw digits: "1234567890"
console.log(values.formattedValue); // "+1 (123) 456-7890"
}}
/>
);
}
// Empty input displays: +1 (___) ___-____
// User types: 1234567890 -> Displays: +1 (123) 456-7890
```
--------------------------------
### Validating input with isAllowed
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/props.md
Implement custom validation logic using the `isAllowed` prop. This function receives the values object and should return a boolean. If it returns false, the change event is prevented.
```javascript
import { NumericFormat } from 'react-number-format';
const MAX_LIMIT = 1000;
{
const { floatValue } = values;
return floatValue < MAX_LIMIT;
}}
/>;
```
--------------------------------
### Displaying Formatted Value as Text
Source: https://context7.com/s-yadav/react-number-format/llms.txt
Use displayType="text" to render the formatted value directly as text, optionally wrapping it with a custom render function.
```jsx
import { NumericFormat, PatternFormat } from 'react-number-format';
import { TextField } from '@mui/material';
// Display as text instead of input
function TextDisplayExample() {
return (
{value}}
/>
);
}
// Renders: $1,231,231
```
--------------------------------
### Define Allowed Decimal Separators
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/numeric_format.md
Use `allowedDecimalSeparators` to specify characters that trigger a decimal separator. If not provided, '.' is used.
```javascript
import { NumericFormat } from 'react-number-format';
;
```
--------------------------------
### Customize Pattern Character
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/pattern_format.md
Use the 'patternChar' prop to define a custom character for the format pattern, instead of the default '#'.
```javascript
import { PatternFormat } from 'react-number-format';
;
```
--------------------------------
### Values Object Structure
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/quirks.md
The 'values' object provides formatted, non-formatted, and float values. Use 'valueIsNumericString' prop if saving the 'value' key to state and formatting props contain numbers.
```js
{
formattedValue: '$23,234,235.56', //value after applying formatting
value: '23234235.56', //non formatted value as numeric string 23234235.56, if you are setting this value to state make sure to pass valueIsNumericString prop to true
floatValue: 23234235.56 //floating point representation. For big numbers it can have exponential syntax
}
```
--------------------------------
### Custom Text Rendering with renderText
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/props.md
Use the renderText prop to render the formatted value in a different HTML element, such as a tag. It also passes custom props that can be applied to the rendered element.
```javascript
import { NumericFormat } from 'react-number-format';
{value}}
/>;
```
--------------------------------
### renderText
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/props.md
A render function that allows formatting the display value in a different HTML element.
```APIDOC
## renderText `(formattedValue, customProps) => React Element`
### Description
A renderText method useful if you want to render `formattedValue` in a different element other than a `span`. It also returns the custom props that are added to the component, which can allow passing down props to the rendered element.
### Default
`undefined`
### Request Example
```javascript
import { NumericFormat } from 'react-number-format';
{value}}
/>;
```
```
--------------------------------
### Change Meta Type Definition
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/numeric_format.md
Defines the structure of `changeMeta` object passed to `removeNumericFormat`, detailing the changes in cursor position and the last value.
```javascript
{
from: {start: number, end: number},
to: {start: number, end: number},
lastValue: string
}
```
--------------------------------
### useNumericFormat Hook
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/numeric_format.md
The useNumericFormat hook encapsulates the core numeric formatting logic. It returns the necessary props that can be passed to NumberFormatBase for rendering formatted numeric inputs. Customization can be achieved by patching the methods returned by this hook.
```APIDOC
## useNumericFormat Hook
### Description
Provides the props required for `NumberFormatBase` by handling the core numeric formatting logic. Allows for customization by patching its returned methods.
### Method
`useNumericFormat`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
- **props** (NumericFormatProps) - Required - The properties object for numeric formatting.
### Request Example
```javascript
import { useNumericFormat } from 'react-number-format';
function MyNumericInput(props) {
const numberFormatProps = useNumericFormat(props);
return ;
}
```
### Response
#### Success Response (200)
- **NumberFormatBaseProps** - An object containing props suitable for `NumberFormatBase`.
#### Response Example
```json
{
"value": "1,234.56",
"onChange": "function",
"onBlur": "function",
// ... other props
}
```
```
--------------------------------
### Apply Mask Character for Numeric Places
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/pattern_format.md
Use the 'mask' prop to specify a character that appears until a numeric character is provided for that position. The length of the mask characters must match the number of pattern characters.
```javascript
import { PatternFormat } from 'react-number-format';
;
```
--------------------------------
### allowNegative Prop
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/numeric_format.md
Determines whether negative numbers are permitted. If set to `false`, the input will not accept negative values.
```APIDOC
## allowNegative Prop
### Description
If set to `false`, negative numbers will not be allowed.
### Type
`boolean`
### Default
`true`
### Usage Example
```js
import { NumericFormat } from 'react-number-format';
;
```
```
--------------------------------
### onValueChange
Source: https://github.com/s-yadav/react-number-format/blob/master/documentation/v5/docs/props.md
A handler that provides access to input field value changes, triggered by prop changes or user input.
```APIDOC
## onValueChange `(values, sourceInfo) => {}`
### Description
This handler provides access to any values changes in the input field and is triggered only when a prop changes or the user input changes. It provides two arguments: `values` (an object containing `formattedValue`, `value`, and `floatValue`) and `sourceInfo` (an object containing the `event` Object and a `source` key indicating the change origin).
**Note**: If you are using `values.value` (which is the non-formatted numeric string), ensure `valueIsNumericString` is set to `true` if any format prop contains a number, or if `thousandSeparator` is `.` in `NumericFormat`.
### Default
`undefined`
### Request Example
```javascript
import { NumericFormat } from 'react-number-format';
{
console.log(values, sourceInfo);
}}
/>;
```
```