Skip to content

Instantly share code, notes, and snippets.

@phatnguyenuit
Last active October 6, 2019 16:05
Show Gist options
  • Save phatnguyenuit/4b2c8145a8738094d406b7d7ee978909 to your computer and use it in GitHub Desktop.
Save phatnguyenuit/4b2c8145a8738094d406b7d7ee978909 to your computer and use it in GitHub Desktop.
Enhance Count Down Component in ReactJS with Typescript
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;
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