Coder Social home page Coder Social logo

vydimitrov / use-count-up Goto Github PK

View Code? Open in Web Editor NEW
410.0 3.0 15.0 1.12 MB

React/React Native component and hook to animate counting up or down to a number

Home Page: https://use-count-up.now.sh/

License: MIT License

JavaScript 5.96% TypeScript 91.05% HTML 3.00%
react animate-counting count-up react-native ios android countup react-countup

use-count-up's Introduction

use-count-up

NPM version Weekly downloads Code Coverage Bundle Size


React/React Native component and hook to animate
counting up or down to a number


Key features

๐Ÿ† Lighter implementation and smaller bundle size in comparison with similar feature solutions
๐ŸŽ Declarative API (no more imperative calls to start() and update())
ย :iphone:ย  React Native support for iOS and Android
๐ŸŒณ Tree-shakable
ย :file_cabinet: Server-side rendering (SSR) compatibility

Installation

yarn add use-count-up

Demo

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 if end is set
decimalPlaces number - Number of decimal places after the decimal separator. Defaults to the max decimal places count from start and end props
decimalSeparator string - Decimal separator character
thousandsSeparator string - Thousands separator character
easing string | function easeOutCubic Type: easeOutCubic | easeInCubic | linear | easing func
Easing function to control the animation progress
formatter function - Type: (value: number) => number | string | node
A function that formats the output value. It has the highest priority so all other formatting options are ignored
updateInterval number 0 Update interval in seconds. Determines how often the animated value will change. When set to 0 the value will update on each key frame
children function - Type: ({ value: number, reset: () => void }) => number | string | node
CountUp component - children prop
onComplete function - Type: () => void | {shouldRepeat: boolean, delay: number}
On complete handler. Repeat animation by returning an object with shouldRepeat equals true and delay in seconds.
onUpdate function - Type: (currentValue: number | string | node) => void
On value update event handler

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 with formatter

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 use the formatter prop, like so:

import { CountUp } from 'use-count-up'

const MyComponent = () => (
  <CountUp
    isCounting
    end={1320}
    formatter={(value) => value.toLocaleString()}
  />
)

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.

Recipes

Reset animation

Pass a key prop to CountUp component and change it when the animation should repeat. It can be also used when a change of start or end value should start the animation over.

import { CountUp } from 'use-count-up'

const MyComponent = ({ end }) => <CountUp isCounting end={end} key={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. The updateInterval can be set to 1, so it updates once every second. 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"
    updateInterval={1}
    onUpdate={(currentValue) => {
      // it will fire once every second
    }}
  />
)

Browser support

The component and hook support all modern browsers targeting es6. Internet Explorer (IE) is not longer supported.

use-count-up's People

Contributors

dependabot[bot] avatar renovate-bot avatar renovate[bot] avatar vydimitrov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

use-count-up's Issues

Dynamically changing values makes animation not work

Hi, since the update 3.0.1, changing values dynamically breaks the animation, the value changes instantly. I prepared a simple example to reproduce the bug.

const [dynamicValue, setValue] = useState<number>(700);

  const { value } = useCountUp({
    isCounting: true,
    start: 200,
    end: dynamicValue,
    duration: 2,
    decimalPlaces: 2
  });

  useEffect(() => {
    setTimeout(() => {
      setValue(2000);
    }, 4000);
  }, []);

The animation starts good, but when the timeout executes, the value changes immediately, before 3.0.1 it worked perfectly.

React Native easing not supported?

import { Easing } from 'react-native'

 <LazyCountUp
  isCounting
  easing={Easing.inOut(Easing.ease)}
  end={1200}
/>

Doesn't seem to work. The number goes negative, and ends at 1

Broken changes with latest version 3.0.1 for React Native

Using

"react-native": "~0.63.3",
"use-count-up": "~3.0.1",

No idea what happens, just crashes my entire application with no error code, I looked at the previous releases and noticed that the last 2 releases had brekaing changes, so I installed

"use-count-up": "^2.3.1"

instead because I don't need any extended features or fancy stuff, I just want to animate some text once, with no button/hooks etc.

Working when I downgrade, however I think you should check this out.

Can't count minutes

<Text><CountUp isCounting={starTimer} start={0} end={180} duration={180} easing="linear"/></Text>
<Text><CountUp isCounting={starTimer} start={0} end={3} duration={180} easing="linear"/></Text>

If I am not mistaken, this two counters should end at the same time, but they don't.

Here's how it works:

The second timer turns to 1 when the first one is at 30.
The second timer turns to 2 when the first one is at 90
The second timer turns to 3 when the first one is at 150.

Am I doing something wrong or it is just not working when trying to count minutes?

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

Dependency Dashboard

This issue provides visibility into Renovate updates and their statuses. Learn more

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.


  • Check this box to trigger a request for Renovate to run again on this repository

Count up does not start if Electron window is in background

Thanks for the great package!

My issue is with background behavior in Electron. I've noticed that if CountUp starts, then is backgrounded, the counting up properly continues. However if the component is rendered while the Electron app is backgrounded, then CountUp wont begin until Electron is brought to the foreground.

Since CountUp is used for displaying time passing, I want it to either (1) start in the background or (2) be updated instantly to the proper value.

Perhaps a setInterval could be used to periodically update it? Curious how you would approach this.

render `end` value in HTML during SSR

Problem:

in SSR generated HTML use-count-up renders 0, instead of end value, which has adverse effects for SEO.

Example

<span><CountUp isCounting end={500} /></span> will result in <span>0</span> in HTML.

Expected:

<span><CountUp isCounting end={500} /></span> should result in <span>500</span> in HTML.

And then on hydration start animating from 0.

Using next.js@12. Likely the same behavior with previous versions as well.

Cannot run in Next.js

When running the simple hello world example from the README, I am getting compile errors from Next.js:

image

I believe it might be internally using an old useState function or something. The only code I added was:

  const { value } = useCountUp({
    isCounting: true,
    end: 1234,
    duration: 3.2,
  })

CodeSandbox Repro: https://codesandbox.io/p/sandbox/elated-wu-mbj41e

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.