Skip to content

Instantly share code, notes, and snippets.

@fdaciuk
Last active December 8, 2022 18:38
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fdaciuk/f5ebc7999839df1bf715ae30f58f3c1c to your computer and use it in GitHub Desktop.
Save fdaciuk/f5ebc7999839df1bf715ae30f58f3c1c to your computer and use it in GitHub Desktop.
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