Skip to content

Instantly share code, notes, and snippets.

@pl12133
Created February 23, 2016 19:45
Show Gist options
  • Save pl12133/16f7e4df463bbcc71b76 to your computer and use it in GitHub Desktop.
Save pl12133/16f7e4df463bbcc71b76 to your computer and use it in GitHub Desktop.
// Problem: How to make a "Loading" spinner or animation appear before a component is fully rendered?
// Solution:
// 1. Allow the component to render once and display a <LoadingSpinner /> component,
// and defer the change of `this.state.loading` until after component renders once
class SomethingWithLoadSpinner extends Component {
constructor(...args) {
super(...args);
this.state = {
loading: true
};
}
componentDidMount () {
// By allowing the component to mount and render once, we allow the <LoadingSpinner /> to appear on the client quickly.
this.setState({
width: document.getElementById('container').clientWidth
}, () => {
setTimeout(() => this.setState({loading: false}), 0);
});
// After rendering once, change loading to false and then rendering of the actual component begins.
}
render () {
if (this.state.loading) {
return (
<div id='container'>
<LoadingSpinner />
</div>
)
} else {
return (
<div id='container'>
{/* All the content goes here */}
</div>
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment