benshepherd icon

NumberCounter.js

benshepherd | PRO | 05/11/19 04:45:41 PM UTC | 0 ⭐ | 353 👁️ | Never ⏰ | []
JavaScript |

1.47 KB

|

None

|

0 👍

/

0 👎

import React from 'react'
 
class NumberCounter extends React.Component {
 
    handle = null
    state = {
        current: 0,
    }
    incrementAmount = 1
 
    componentDidMount() {
        this.incrementAmount = this.props.target / 60
        this.handleCount()
    }
 
    componentWillUnmount() {
        this.setState({current: 0})
        clearInterval(this.handle)
    }
 
    componentWillReceiveProps(nextProps) {
        if(nextProps.target !== this.props.target) {
            this.setState({ current: 0 }, () => {
                this.handleCount()
            })
        }
    }
 
    handleCount() {
        this.handle = setInterval(() => {
            let current = this.state.current
            const target = this.props.target
 
            if(current < target) {
                current += this.incrementAmount
                this.setState({ current: Math.floor(current) })
            }
            else {
                this.setState({ current: target })
                clearInterval(this.handle)
            }
        }, 1);
    }
 
    render() {
        const {
            current,
        } = this.state
        const {
            text,
            target,
        } = this.props
 
        return (
            <div className="NumberCounter">
                <div className="number">{current}</div>
                <div className="text">{text}</div>
            </div>
        )
    }
}
 
export default NumberCounter

Comments