Skip to content

Instantly share code, notes, and snippets.

@JohannesFischer
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JohannesFischer/26b30a84584e29ce886e to your computer and use it in GitHub Desktop.
Save JohannesFischer/26b30a84584e29ce886e to your computer and use it in GitHub Desktop.
"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