Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement