Skip to content

Instantly share code, notes, and snippets.

@steida
Last active August 29, 2015 14:19
Show Gist options
  • Save steida/9d80c9858d1bc31741d1 to your computer and use it in GitHub Desktop.
Save steida/9d80c9858d1bc31741d1 to your computer and use it in GitHub Desktop.
Loading Pure component
import PureComponent from './purecomponent.react'
import React from 'react'
import classnames from 'classnames'
import {msg} from '../intl/store'
require('./loading.styl')
export default class Loading extends PureComponent {
constructor(props) {
super(props)
this.state = {
shown: false
}
}
// To prevent load messages blinking. It doesn't make sense to show text <1s.
hideNowShowLater() {
this.setState({shown: false})
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.setState({
shown: true
})
}, this.props.delay)
}
componentDidMount() {
this.hideNowShowLater()
}
componentWillReceiveProps(nextProps) {
if (nextProps.loaded) return
this.hideNowShowLater()
}
componentWillUnmount() {
clearTimeout(this.timer)
}
render() {
const className = classnames('loading-component', {
loaded: this.props.loaded,
shown: this.state.shown
})
const children = this.props.loaded
? this.props.children
: this.state.shown
? this.props.message || msg('components.loading.message')
: ''
return (
<div className={className}>{children}</div>
)
}
}
Loading.propTypes = {
children: React.PropTypes.node,
delay: React.PropTypes.number,
loaded: React.PropTypes.bool,
message: React.PropTypes.string
}
Loading.defaultProps = {
// http://www.nngroup.com/articles/response-times-3-important-limits/
delay: 1000,
loaded: false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment