Created
February 23, 2016 19:45
-
-
Save pl12133/16f7e4df463bbcc71b76 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 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