Last active
August 29, 2015 14:27
-
-
Save JohannesFischer/26b30a84584e29ce886e to your computer and use it in GitHub Desktop.
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" | |
ImageLoader = React.createClass | |
displayName: 'ImageLoader' | |
propTypes: | |
altSrc: React.PropTypes.string | |
attributes: React.PropTypes.object | |
className: React.PropTypes.string | |
onError: React.PropTypes.func | |
onLoad: React.PropTypes.func | |
src: React.PropTypes.string.isRequired | |
wrapper: React.PropTypes.string | |
getDefaultProps: -> | |
attributes: {} | |
className: '' | |
wrapper: 'span' | |
getInitialState: -> | |
status: 'pending' | |
componentDidMount: -> | |
@createLoader() | |
componentWillReceiveProps: (nextProps) -> | |
if @props.src isnt nextProps.src | |
@setState | |
status: nextProps.src ? 'loading' : 'pending' | |
componentDidUpdate: -> | |
if @state.status is 'loading' && !@img | |
@createLoader() | |
componentWillUnmount: -> | |
@destroyLoader() | |
createLoader: -> | |
@destroyLoader() | |
@img = new Image() | |
@img.onload = @handleLoad | |
@img.onerror = @handleError | |
@img.src = @props.src | |
destroyLoader: -> | |
if @img | |
@img.onload = null | |
@img.onerror = null | |
@img = null | |
handleLoad: (event) -> | |
@destroyLoader() | |
@setState | |
status: 'loaded' | |
if @props.onLoad then @props.onLoad(event) | |
handleError: (error) -> | |
@destroyLoader() | |
@setState | |
status: 'error' | |
if @props.onError then @props.onError(error) | |
getAttributes: (src) -> | |
attributes = @props.attributes | |
attributes.src = src | |
attributes | |
render: -> | |
if @state.status is 'pending' | |
# show loader | |
else if @state.status is 'loading' | |
# show loader | |
else if @state.status is 'loaded' | |
attributes = @getAttributes @props.src | |
img = React.createElement 'img', attributes | |
else | |
# insert placeholder | |
if @props.altSrc | |
attributes = @getAttributes @props.altSrc | |
img = React.createElement 'img', attributes | |
React.createElement @props.wrapper, { | |
className: "image-#{@state.status} #{@props.className}" | |
}, img | |
window.ImageLoader = ImageLoader |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment