Last active
October 6, 2019 16:05
-
-
Save phatnguyenuit/4b2c8145a8738094d406b7d7ee978909 to your computer and use it in GitHub Desktop.
Enhance Count Down Component in ReactJS with Typescript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import { EnhanceCountDownPropsType, EnhanceCountDownStateType } from './types'; | |
class EnhanceCountDown extends React.PureComponent< | |
EnhanceCountDownPropsType, | |
EnhanceCountDownStateType | |
> { | |
countDownInterval?: number; | |
constructor(props: EnhanceCountDownPropsType) { | |
super(props); | |
const { timeout } = this.props; | |
this.state = { | |
timeout, | |
pending: false, | |
finished: false, | |
}; | |
} | |
countDown = () => { | |
const { timeout } = this.state; | |
const { decreaseTimeout = 1 } = this.props; | |
if (!!this.countDownInterval && timeout <= 0) { | |
clearInterval(this.countDownInterval); | |
this.setState({ | |
pending: false, | |
finished: true, | |
}); | |
} else { | |
this.setState((prev: EnhanceCountDownStateType) => { | |
let newTimeout = prev.timeout - decreaseTimeout; | |
newTimeout = newTimeout < 0 ? 0 : newTimeout; | |
return { | |
timeout: newTimeout, | |
}; | |
}); | |
} | |
}; | |
enhanceCountDown = () => { | |
const { intervalTimeout = 1000 } = this.props; | |
this.setState({ | |
pending: true, | |
}); | |
if (!this.countDownInterval) { | |
this.countDownInterval = setInterval(this.countDown, intervalTimeout); | |
} | |
}; | |
render() { | |
const { children } = this.props; | |
return children({ | |
...this.state, | |
enhanceCountDown: this.enhanceCountDown, | |
}); | |
} | |
} | |
export default EnhanceCountDown; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface EnhanceCountDownPropsType { | |
timeout: number; | |
decreaseTimeout?: number; | |
intervalTimeout?: number; | |
children(props: InjectedCountDownProps): JSX.Element; | |
} | |
export interface EnhanceCountDownStateType { | |
finished: boolean; | |
pending: boolean; | |
timeout: number; | |
} | |
interface InjectedCountDownProps extends EnhanceCountDownStateType { | |
enhanceCountDown: Function; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment