Last active
June 18, 2020 11:53
-
-
Save Grohden/23984bf94ec2f3a8a9b2a51254b68ee5 to your computer and use it in GitHub Desktop.
SIMPLE react native currency input for brazilian currency
This file contains 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
/* eslint-disable @typescript-eslint/no-magic-numbers */ | |
import { useRefCallback } from '@hooks/useRefCallback' | |
import React from 'react' | |
import { StyleProp, ViewStyle } from 'react-native' | |
import { TextInput } from 'react-native-paper' | |
type Props = { | |
label: string | |
value: number | |
onChangeValue: (value: number) => void | |
style: StyleProp<ViewStyle> | |
} | |
// We could try toLocaleString with currency and stuff, | |
// but: https://github.com/facebook/hermes/issues/23 | |
const formatValue = (value: number) => { | |
return `R$ ${value.toFixed(2)}` | |
} | |
const CurrencyInput = (props: Props) => { | |
const currency = formatValue(props.value) | |
const handleChange = useRefCallback((rawValue: string) => { | |
const value = rawValue | |
.replace(/[^0-9.-]+/, '') | |
.replace(/[.,]/g, '') | |
props.onChangeValue(Number(value) / 100) | |
}) | |
return ( | |
<TextInput | |
autoCorrect={ false } | |
style={ props.style } | |
keyboardType='numeric' | |
label={ props.label } | |
value={ currency } | |
onChangeText={ handleChange } | |
/> | |
) | |
} | |
export default CurrencyInput |
This file contains 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
/* eslint-disable @typescript-eslint/no-explicit-any */ | |
import useFreshRef from './useFreshRef' | |
import { useCallback } from 'react' | |
// Makes the use callback more automatic | |
// by always invoking the latest render ref | |
// But be warned that this may cause PROBLEMS | |
// if it's used to memoize callbacks that return renders | |
// and need to be changed. | |
// For example, FlatList will not re-render | |
// if you memoize the renderItems callback with this | |
export const useRefCallback = < | |
T extends (...args: any[]) => any | |
>(cb: T) => { | |
// useFreshRef is a ref that updates the `current` in every render. | |
const cbRef = useFreshRef(cb) | |
return useCallback((...args) => cbRef.current( | |
...args | |
), []) as unknown as T | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment