An image component for gracefully dealing with image errors, by providing optional lazy loading, an optional placeholder and retries on failure. Particularly useful in situations where your application might be used in poor signal areas such as when travelling on a train, a bus or a car.
(note: these are not mutually exclusive, for example the default behaviour makes use of both a placeholder and retries together.)
Placeholder
placeholderColor
prop — as well as via a regular styles
or className
props ( note that styles passed this way are also passed to the actual image.)Retry
setTimeout
which plays around with the delay and the desired number of retries in an attempt to gracefully re-load the imageretry.accumulate
prop which accepts one of the following values ‘multiply’, ‘add’, ‘noop’ and updates the retry algorithm accordingly (note you can also change the delay time and retry count)The below code snippet will display a blue SVG placeholder, if it is within the visible viewport then it will load the actual given image and fade it in once it is done loading. If loading the image fails, then it will retry loading the image again for a maximum of 8 times, with initial delay of 2 seconds, which will then increase to 4 seconds, then to 8 seconds, then to 16 seconds, and so on (default retry configuration). It will also apply whatever styles are defined inside of the ‘content-image’ className to the placeholder (and the image once the image loads).
import React, { Component } from 'react'import Image from 'react-graceful-image'
class YourComponent extends Component {render() {return (<Imagesrc="path_to_image"className="content-image"alt="My awesome image"placeholderColor="#0083FE"/>);}}
The below code snippet will display a light grey (default) SVG placeholder, if it is within the visible viewport then it will load the actual given image and fade it in once it is done loading. If loading the image fails, then it will retry loading the image again for a maximum of 15 times, with initial delay of 3 seconds which will then increase to 6 seconds, then to 9 seconds, then to 12 seconds, and so on. It will apply 20px of padding to the placeholder (and the image once the image loads).
import React, { Component } from 'react'import Image from 'react-graceful-image'
class YourComponent extends Component {render() {return (<Imagesrc="path_to_image"width="150"height="150"style={{padding: '20px'}}alt="My awesome image"retry={{count: 15, delay: 3, accumulate: 'add'}}/>);}}
Thanks for reading, for more usage details checkout the projects github page: https://github.com/linasmnew/react-graceful-image. You can also install it via npm using: npm install --save react-graceful-image