Skip to content

Commit

Permalink
feat: add <WhenIdle> component
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Feb 24, 2018
1 parent ac75ff5 commit 3d39f38
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/WhenIdle/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import {Component} from 'react';

const RIC = (window as any).requestIdleCallback || ((fn, {timeout = 35} = {}) => setTimeout(fn, 35));

export interface IWhenIdleProps {
timeout?: number;
}

export interface IWhenIdleState {
ready: boolean;
}

export class WhenIdle extends Component<IWhenIdleProps, IWhenIdleState> {
mounted = false;

state: IWhenIdleState = {
ready: false
};

componentDidMount () {
this.mounted = true;

const {timeout} = this.props;

RIC(() => {
if (this.mounted) {
this.setState({ready: true});
}
}, {timeout});
}

componentWillUnmount () {
this.mounted = false;
}

render () {
return this.state.ready ? this.props.children : null;
}
}

0 comments on commit 3d39f38

Please sign in to comment.