-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
Showing
1 changed file
with
45 additions
and
20 deletions.
There are no files selected for viewing
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
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; |