Advertisement
benshepherd

NumberCounter.js

May 11th, 2019
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React from 'react'
  2.  
  3. class NumberCounter extends React.Component {
  4.  
  5.     handle = null
  6.     state = {
  7.         current: 0,
  8.     }
  9.     incrementAmount = 1
  10.  
  11.     componentDidMount() {
  12.         this.incrementAmount = this.props.target / 60
  13.         this.handleCount()
  14.     }
  15.  
  16.     componentWillUnmount() {
  17.         this.setState({current: 0})
  18.         clearInterval(this.handle)
  19.     }
  20.  
  21.     componentWillReceiveProps(nextProps) {
  22.         if(nextProps.target !== this.props.target) {
  23.             this.setState({ current: 0 }, () => {
  24.                 this.handleCount()
  25.             })
  26.         }
  27.     }
  28.  
  29.     handleCount() {
  30.         this.handle = setInterval(() => {
  31.             let current = this.state.current
  32.             const target = this.props.target
  33.  
  34.             if(current < target) {
  35.                 current += this.incrementAmount
  36.                 this.setState({ current: Math.floor(current) })
  37.             }
  38.             else {
  39.                 this.setState({ current: target })
  40.                 clearInterval(this.handle)
  41.             }
  42.         }, 1);
  43.     }
  44.  
  45.     render() {
  46.         const {
  47.             current,
  48.         } = this.state
  49.         const {
  50.             text,
  51.             target,
  52.         } = this.props
  53.  
  54.         return (
  55.             <div className="NumberCounter">
  56.                 <div className="number">{current}</div>
  57.                 <div className="text">{text}</div>
  58.             </div>
  59.         )
  60.     }
  61. }
  62.  
  63. export default NumberCounter
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement