Created
November 14, 2018 18:01
-
-
Save tomfordweb/bac046b64550476c9c1569fd13ab7a88 to your computer and use it in GitHub Desktop.
Hide Image until it has been loaded. Not a promise.
This file contains hidden or 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
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
const hiddenImageStyle = { | |
width: 0, | |
height: 0 | |
}; | |
class LoadableImage extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
loaded: false | |
}; | |
} | |
imageLoaded() { | |
this.setState({ | |
loaded: true | |
}); | |
} | |
render() { | |
if (this.state.loaded) { | |
return( <img | |
alt={this.props.alt} | |
src={this.props.url} | |
{...this.props} | |
/>) | |
} | |
const { alt, url } = this.props; | |
return (<img | |
src={url} | |
alt={alt} | |
onLoad={() => this.imageLoaded()} | |
style={hiddenImageStyle} | |
/> | |
); | |
} | |
} | |
LoadableImage.defaultProps = { | |
alt: '', | |
} | |
LoadableImage.propTypes = { | |
url: PropTypes.string.isRequired, | |
alt: PropTypes.string, | |
} | |
export default LoadableImage; |
This file contains hidden or 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
import React from 'react'; | |
import { expect } from 'chai'; | |
import LoadableImage from './LoadableImage'; | |
import { mount, shallow, render } from 'enzyme'; | |
describe('<LoadadableImage /> ', () => { | |
const img = shallow(<LoadableImage url="example.jpg" alt="some alt text" />); | |
const imgStyle = img.get(0).props.style; | |
it('can render an image', () => { | |
expect(img.props().src).to.equal('example.jpg'); | |
}) | |
it('can render the alt tag', () => { | |
expect(img.props().alt).to.equal('some alt text'); | |
}) | |
it('can hide the image if it hasnt been loaded', () => { | |
expect(imgStyle).to.contain({width: 0}); | |
expect(imgStyle).to.contain({height: 0}); | |
}) | |
it('can show the image if it has been loaded', () => { | |
const mountable = mount(<LoadableImage url="example.jpg" alt="some alt text" id="seemeonload" />); | |
const inst = mountable.instance(); | |
inst.imageLoaded(); | |
expect(mountable.props().id).to.equal('seemeonload'); | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment