React Lazy img load component
This file contains 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
'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