Skip to content

Commit

Permalink
feat: improve <AfterDraf>
Browse files Browse the repository at this point in the history
Make <AfterDraf> work on server. As well as allow users to create their
custom <AfterDraf>s, which wait for DRAF only a given number of times,
for example, to prevent FOUC, your component needs to wait for DRAF only
for the first time but subsequent re-renders can render children
synchronously.
  • Loading branch information
streamich committed Apr 19, 2018
1 parent 22a106c commit f567d58
Showing 1 changed file with 45 additions and 20 deletions.
65 changes: 45 additions & 20 deletions src/AfterDraf/index.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,56 @@
import {Component} from 'react';

const RAF = requestAnimationFrame;
import {isClient} from '../util';

export interface IAfterDrafState {
ready: boolean;
}

export class AfterDraf extends Component<{}, IAfterDrafState> {
frame;
const Passthrough = (props) => props.children;

state: IAfterDrafState = {
ready: false
};
export const createAfterDraf = (times = 1) => {
let cnt = 0;

componentDidMount () {
this.frame = RAF(() => {
this.frame = RAF(() => {
this.setState({ready: true});
});
});
}
return class extends Component<{}, IAfterDrafState> {
frame;
state: IAfterDrafState;

componentWillUnmount () {
cancelAnimationFrame(this.frame);
}
constructor (props, context) {
super(props, context);

if (isClient && cnt < times) {
this.state = {
ready: false
};
}
}

componentDidMount () {
if (isClient && cnt < times) {
const RAF = requestAnimationFrame;

render () {
return this.state.ready ? this.props.children : null;
this.frame = RAF(() => {
this.frame = RAF(() => {
cnt++;
this.setState({ready: true});
});
});
}
}

componentWillUnmount () {
if (isClient && cnt < times) {
cancelAnimationFrame(this.frame);
}
}

render () {
if (!isClient || cnt >= times) {
return this.props.children;
}

return this.state.ready ? this.props.children : null;
}
}
}
};

export const AfterDraf = isClient ? createAfterDraf(Infinity) : Passthrough;

0 comments on commit f567d58

Please sign in to comment.