Created
January 28, 2025 21:59
-
-
Save MForMarlon/0576bd8dde897b9468d5ddb11ce63671 to your computer and use it in GitHub Desktop.
I asked Gemini to make me a React component that can be entered like a price with international number formatting support. We'll see if this works.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React, { useState, useEffect } from 'react'; | |
| const PriceInput = ({ | |
| value: initialValue, | |
| currencyCode, | |
| useATMInput = false, | |
| allowDecimals = true, | |
| onBlur, | |
| className, | |
| disabled | |
| }) => { | |
| const [currentValue, setCurrentValue] = useState(initialValue || ''); | |
| useEffect(() => { | |
| const userLocale = navigator.language; | |
| const formatter = new Intl.NumberFormat(userLocale, { | |
| style: 'currency', | |
| currency: currencyCode, | |
| }); | |
| const formattedValue = formatter.format(parseFloat(currentValue)); | |
| setCurrentValue(formattedValue); | |
| }, [currentValue, currencyCode]); | |
| const handleChange = (event) => { | |
| if (disabled) return; // Prevent changes if disabled | |
| let cleanedValue = event.target.value.replace(/[^\d]/g, ''); | |
| if (useATMInput) { | |
| cleanedValue = currentValue + cleanedValue; | |
| } | |
| const decimalSeparator = '.'; | |
| const groupSeparator = ','; | |
| if (!allowDecimals) { | |
| cleanedValue = cleanedValue.replace(decimalSeparator, ''); | |
| } | |
| // Allow only one decimal point | |
| const hasDecimal = cleanedValue.includes(decimalSeparator); | |
| const cleanedValueWithDecimal = hasDecimal | |
| ? cleanedValue.replace(decimalSeparator, '').replace(groupSeparator, decimalSeparator).replace(new RegExp('\\' + groupSeparator, 'g'), '') | |
| : cleanedValue.replace(groupSeparator, ''); | |
| // Reformat with thousands separator | |
| const parts = cleanedValueWithDecimal.split(decimalSeparator); | |
| parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, groupSeparator); | |
| const formattedValue = parts.join(decimalSeparator); | |
| setCurrentValue(formattedValue); | |
| }; | |
| return ( | |
| <input | |
| type="text" | |
| value={currentValue} | |
| onChange={handleChange} | |
| onBlur={() => { | |
| if (currentValue !== initialValue && onBlur) { | |
| onBlur(); | |
| } | |
| }} | |
| placeholder="Enter Price" | |
| className={className} | |
| disabled={disabled} | |
| /> | |
| ); | |
| }; | |
| export default PriceInput; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment