

React Native component and hook to animate counting up or down to a number
source link: https://reactnativeexample.com/react-native-component-and-hook-to-animate-counting-up-or-down-to-a-number/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

use-count-up
React/React Native component and hook to animate counting up or down to a number.
Key features
:trophy: Lighter implementation and smaller bundle size in comparison with similar feature solutions
:scroll: Support toLocaleString
with fallback options
:flags: Declarative API (no more imperative calls to start()
and update()
)
:iphone: React Native support for iOS and Android
:deciduous_tree: Tree-shakable (minified size further reduced by ~ 0.4kB when only the hook is used)
:file_cabinet: Server-side rendering (SSR) compatibility
Installation
yarn add use-count-up
Check the React demo on CodeSandbox and React Native demo on Expo Snack to get started.
Component basic usage
import { CountUp } from 'use-count-up'
const MyComponent = () => <CountUp isCounting end={1320} duration={3.2} />
The CountUp
component should be wrapped in a Text
component when used in a React Native project like so:
import { Text } from 'react-native'
import { CountUp } from 'use-count-up'
const MyComponent = () => (
<Text>
<CountUp isCounting end={1320} duration={3.2} />
</Text>
)
Hook basic usage
The hook accepts the same properties as the component. The usage for React and React Native is the same.
import { useCountUp } from 'use-count-up'
const MyComponent = () => {
const { value } = useCountUp({
isCounting: true,
end: 1320,
duration: 3.2,
})
return value
}
Props
The component and the hook accept the same props. They are fully interchangeable.
Prop Name Type Default Description isCounting boolean false Play and pause counting animation start number 0 Initial value end number - Target value duration number - Animation duration in seconds. Defaults to 2 seconds ifend
is set. If end
isn't set, the animation will continue to Infinity.
decimalPlaces
number
-
Number of decimal places after the decimal separator. Defaults to the max decimal places count from start
and end
decimalSeparator
string
-
Decimal separator character
thousandsSeparator
string
-
Thousands separator character
prefix
string
-
Static text before the value
suffix
string
-
Static text after the value
shouldUseToLocaleString
boolean
false
Indicates if toLocaleString
should be used
toLocaleStringParams
{ locale, options }
-
Set toLocaleString
locale and/or options by passing an object with locale
and/or options
keys. Read more here
fallbackPrefix
string
-
Static text before the value to be used in case toLocaleString
params are not supported
fallbackSuffix
string
-
Static text after the value to be used in case toLocaleString
params are not supported
autoResetKey
number | string
-
Auto reset animation when the key changes. Works similarly to React key
prop
easing
string | function
easeOutCubic
Type: easeOutCubic | easeInCubic | linear | easing func Easing function to control the animation progress onComplete function - Type: () => void | {shouldRepeat: boolean, delay: number}
On complete handler. It can be used to repeat the animation by returning an object with the following props:
shouldRepeat
indicates if the animation should start over; delay
specifies the delay before looping again in seconds.
formatter
function
-
Type: (value: number) => number | string | node A function that formats the output value. It has the highest priority so all other formating options are ignored children function - Type: ({ value: number, reset: () => void }) => number | string | node
Render function to render the count up value. Used only by the component
Return values
The hook returns the current count up value and reset method to reset the animation.
import { useCountUp } from 'use-count-up'
const { value, reset } = useCountUp({ isCounting: true })
The component's children render function will receive as props the current count up value and reset method to reset the animation.
import { CountUp } from 'use-count-up'
const MyComponent = () => (
<CountUp isCounting>{({ value, reset }) => value}</CountUp>
)
Why use toLocaleString
Number formatting varies per language group. For example, the number 3842.45
in German will be formatted as 3.842,45
whereas in British English it will be 3,842.45
(spot the different decimal and thousands separators). Number.toLocaleString()
is a built-in JS method that returns a string with a language-sensitive representation of the number. The basic implementation of the method will detect the default locale that is set up on the user's computer and will format the number accordingly. The browser support for toLocaleString
is incredibly good.
If you expect variance in the geographical/country distribution of your users, then this is a must. The simplest way to use toLocaleString
with the Count up component or hook is to pass shouldUseToLocaleString: true
like so:
import { CountUp } from 'use-count-up'
const MyComponent = () => (
<CountUp isCounting end={1320} shouldUseToLocaleString />
)
toLocaleString
method accepts an object with two parameters, locale
and options
, which allows further customization of the number value. Setting up the first parameter, locale
, allows the use of a specific locale and fallback option. The second parameter, options
, will let you format the value in a custom way. For example, you may choose to add a min and max number of decimal places, or set currency.
Keep in mind though that the locale
and options
arguments are not supported in all browsers. Despite that, the Count up library offers fallback options in case you need to support obsolete or niche browsers.
Setting up toLocaleString
params without fallback options:
import { useCountUp } from 'use-count-up'
const MyComponent = () => {
const { value } = useCountUp({
isCounting: true,
end: 1320,
//enable toLocaleString and set params
shouldUseToLocaleString: true,
toLocaleStringParams: {
locale: 'de-DE',
options: { style: 'currency', currency: 'EUR', maximumFractionDigits: 2 },
},
})
return value
}
Setting up toLocaleString
params with fallback options:
import { useCountUp } from 'use-count-up'
const MyComponent = () => {
const { value } = useCountUp({
isCounting: true,
end: 1320,
shouldUseToLocaleString: true,
toLocaleStringParams: {
locale: 'de-DE',
options: { style: 'currency', currency: 'EUR', maximumFractionDigits: 2 },
},
// fallback options
decimalPlaces: 2,
decimalSeparator: ',',
thousandsSeparator: '.',
fallbackSuffix: '€',
})
return value
}
Recipes
Reset animation on any prop change
Pass the value of the prop that should reset the animation to autoResetKey
. The most common use case here is resetting the animation when the end
value changes. Example:
import { CountUp } from 'use-count-up'
const MyComponent = ({ end }) => (
<CountUp isCounting end={end} autoResetKey={end} />
)
Repeat animation on completion
Return from the onComplete
handler an object with key shouldRepeat: true
. Optionally the delay
before repeating can be set. In the example below the animation will be repeated in 2 seconds
import { CountUp } from 'use-count-up'
const onComplete = () => {
// do your stuff here
return { shouldRepeat: true, delay: 2 }
}
const MyComponent = () => (
<CountUp isCounting end={4378.2} onComplete={onComplete} />
)
Count up to infinity
Don't provide end
and duration
props. start
prop can be set to any value
import { CountUp } from 'use-count-up'
const MyComponent = () => <CountUp isCounting start={1024.4} />
Count up/down n-seconds
Set the easing
to "linear" and duration
to the seconds it should count up/down. Here is an example of a 10-second count-down:
import { CountUp } from 'use-count-up'
const MyComponent = () => (
<CountUp isCounting start={10} end={0} duration={10} easing="linear" />
)
GitHub
React/React Native component and hook to animate counting up or down to a number — Read More
Recommend
-
118
Make web animation simple :clap: Features: Simple animation from inline style A to style B
-
11
react-fluid-form Reactive forms for react and react native, using hooks and Mobx@6. Installation: npm install -s react-fluid-form mobx mobx-react yup lodash // or: yarn add react-fluid-form mobx mobx-reac...
-
4
Counting the number of matching characters in two ASCII strings Suppose that you give me two ASCII strings having the same number of characters. I wish to compute efficiently the number of matching characters (same position, sa...
-
6
use-auto-focus-inputs Single react-native hook to manage auto focus of TextInput Check out e...
-
4
How to avoid creating a new file by counting the number of files in a folder advertisements I have a software on my computer whe...
-
10
react-native-use-file-upload A hook for uploading files using multipart form data with React Native. Provides a simple way to track upload progress, abort an upload, and handle timeouts. Written in TypeScript and no dependencies required....
-
5
-
9
Difference Between React Component Tests and React Hook Tests
-
5
react-native-animated-stopwatch-timer A React Native Stopwatch/Timer component that empowers reanimated worklets to smoothly animate the digit change. Cross-platform, performant, with all layout animations executed on the UI...
-
9
React Native International Phone Number Input
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK