import React, { useState, useEffect } from 'react';
const CurrencyInput = ({
value,
onChange,
decimalPlaces = 2,
prefix = '$',
placeholder = '0.00',
...props
}) => {
const [displayValue, setDisplayValue] = useState('');
// Update display value when external value changes
useEffect(() => {
if (value === undefined || value === null || value === '') {
setDisplayValue('');
} else {
// Ensure we're working with a number
const numValue = typeof value === 'string' ? parseFloat(value) : value;
if (!isNaN(numValue)) {
setDisplayValue(numValue.toFixed(decimalPlaces));
}
}
}, [value, decimalPlaces]);
const handleChange = (e) => {
const inputValue = e.target.value;
// Allow only digits and at most one decimal point
if (/^[0-9]*\.?[0-9]*$/.test(inputValue)) {
setDisplayValue(inputValue);
// Provide numeric value to onChange handler
if (inputValue === '' || inputValue === '.') {
onChange && onChange('');
} else {
const numValue = parseFloat(inputValue);
if (!isNaN(numValue)) {
onChange && onChange(numValue);
}
}
}
};
const handleBlur = () => {
// Format to fixed decimal places on blur
if (displayValue && displayValue !== '.') {
const numValue = parseFloat(displayValue);
if (!isNaN(numValue)) {
const formatted = numValue.toFixed(decimalPlaces);
setDisplayValue(formatted);
onChange && onChange(parseFloat(formatted));
}
} else {
setDisplayValue('');
onChange && onChange('');
}
};
return (
<div style={{ position: 'relative', display: 'inline-block' }}>
<span
style={{
position: 'absolute',
left: '8px',
top: '50%',
transform: 'translateY(-50%)',
pointerEvents: 'none'
}}
>
{prefix}
</span>
<input
type="text"
value={displayValue}
onChange={handleChange}
onBlur={handleBlur}
placeholder={placeholder}
style={{ paddingLeft: `${prefix.length + 10}px` }}
{...props}
/>
</div>
);
};
export default CurrencyInput;
Would you like me to explain how this code works?