Files
tanami-admin-panel/src/Components/CurrencyInput.jsx

49 lines
1.3 KiB
React
Raw Normal View History

2024-08-12 12:22:01 +05:30
import React, { forwardRef } from 'react';
import { Input } from "@chakra-ui/react";
2024-08-16 15:12:37 +05:30
// export const formatCurrency = (value) => {
// if (!value) return '';
// const [integer, decimal] = value.split('.');
// const formattedInteger = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
// return decimal ? `${formattedInteger}.${decimal}` : formattedInteger;
// };
2024-08-12 12:22:01 +05:30
export const formatCurrency = (value) => {
if (!value) return '';
2024-08-16 15:02:02 +05:30
const [integer, decimal] = value?.split('.');
const formattedInteger = integer?.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
2024-08-12 12:22:01 +05:30
return decimal ? `${formattedInteger}.${decimal}` : formattedInteger;
};
const CurrencyInput = forwardRef(({ value, onChange, ...props }, ref) => {
2024-08-16 15:02:02 +05:30
2024-08-13 16:56:17 +05:30
2024-08-12 12:22:01 +05:30
const handleChange = (event) => {
2024-08-14 12:19:27 +05:30
let { value } = event?.target;
2024-08-12 12:22:01 +05:30
// Remove non-numeric characters except decimal point
2024-08-14 12:19:27 +05:30
value = value?.replace(/[^0-9.]/g, '');
2024-08-12 12:22:01 +05:30
// Ensure only one decimal point
2024-08-14 12:19:27 +05:30
const parts = value?.split('.');
2024-08-12 12:22:01 +05:30
if (parts.length > 2) {
2024-08-14 12:19:27 +05:30
value = parts[0] + '.' + parts?.slice(1)?.join('');
2024-08-12 12:22:01 +05:30
}
onChange(value); // Pass the raw value to parent or use it directly
};
return (
<Input
{...props}
ref={ref} // Forward ref here
type="text"
value={formatCurrency(value)}
onChange={handleChange}
/>
);
});
export default CurrencyInput;