Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React Lazy img load component
'use strict'
import React, { Component } from 'react'
import PropTypes from 'prop-types'
class LazyImg extends Component {
constructor () {
super()
this.state = { loaded: false }
this.img = {}
this.handleLoad = () => {
this.setState({ loaded: true })
this.props.onImageLoad()
}
}
componentDidMount () {
if (this.img.complete && !this.state.loaded) {
this.handleLoad()
}
}
render () {
return (
<img src={this.props.src}
alt={this.props.alt}
onLoad={this.handleLoad}
className={
`[ lazy-image ] ${this.state.loaded ? '-loaded' : ''}
${this.props.className}`
}
ref={(img) => {this.img = img}}
/>
)
}
}
LazyImg.defaultProps = {
onImageLoad: () => null,
className: '',
alt: ''
};
LazyImg.propTypes = {
src: PropTypes.string.isRequired,
className: PropTypes.string,
onImageLoad: PropTypes.func,
alt: PropTypes.string
};
export default LazyImg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment