Skip to content

Repository files navigation

react-load-image

This is a fork of https://github.com/hzdg/react-imageloader, however many design changes were made and deprecations fixed so it warranted its own repo/package.

This React component allows you to display content while waiting for the image to load, as well as by showing alternate content if the image fails to load.

Installing

npm i react-load-image

Usage

importReactfrom'react';importImageLoaderfrom'react-load-image';functionPreloader(props){return<imgsrc="spinner.gif"/>;}React.render((<ImageLoadersrc="/path/to/image.jpg"><img/><div>Error!</div><Preloader/></ImageLoader>),document.body);

Props

NameTypeDescription
onErrorfunctionAn optional handler for the [error] event.
onLoadfunctionAn optional handler for the [load] event.
srcstringThe URL of the image to be loaded, will be passed as the src prop to your first child provided. If you want to use it as a background image, make your first child a react component like Name = (props) => <div style={{backgroundImage: props.src}}/> and do
srcSetstringAn optional value for the srcset attribute of the img

Children

The first child of ImageLoader will be rendered when the image is successfully loaded. The src prop will be passed to it.

The second child of ImageLoader will be rendered when the image load fails.

The third child of ImageLoader will be rendered when the image is in the process of loading

Avoiding duplication Example

importReactfrom'react';importImageLoaderfrom'react-load-image';importImageErrorfrom'./ImageError';importImageLoadingfrom'./ImageLoading';constImage=(props)=><ImageLoader{...props}>{this.props.children[0]}<ImageError/><ImageLoader/></ImageLoader>exportdefaultImage;

importImagefrom'./Image';
...
<Imagestyle={{width: '50px'}}><imgstyle={{border: none}}/></Image>...

Using it as a backgroundImage

importReactfrom'react';constBackgroundImage=({src, style ={}, ...props}={})=><divstyle={Object.assign({backgroundImage: `url(${src})`},style)}{...props}/>exportdefaultBackgroundImage;
<Imagestyle={{width: '50px'}}><BackgroundImage/></Image>

About

Lets you declaratively render different react components based on an image's download state => loading/error/loaded

Resources

Stars

44 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages