Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-image

mbrevda334.6kMIT4.1.0TypeScript support: included

React Image is an tag replacement for react, featuring preloader and multiple image fallback support

reactjs, img, image, loader, fallback, react image, react-image, react img multi, react-img-multi, react image fallback, react image loader, react image preloader, react images, placeholder, placeholders, react image transition, react image fade, image transition, image fade

readme

React Image 🏝 🏖 🏜

npm npm npm npm Known Vulnerabilities

React Image is an <img> tag replacement and hook for React.js, supporting fallback to alternate sources when loading an image fails.

React Image allows one or more images to be used as fallback images in the event that the browser couldn't load the previous image. When using the component, you can specify any React element to be used before an image is loaded (i.e. a spinner) or in the event that the specified image(s) could not be loaded. When using the hook this can be achieved by wrapping the component with <Suspense> and specifying the fallback prop.

React Image uses the useImage hook internally which encapsulates all the image loading logic. This hook works with React Suspense by default and will suspend painting until the image is downloaded and decoded by the browser.

Getting started

  1. To include the code locally in ES6, CommonJS, or UMD format, install react-image using npm:
npm install react-image --save
  1. To include the code globally from a cdn:
<script src="https://unpkg.com/react-image/umd/index.js"></script>

Dependencies

react-image has no external dependencies, aside from a version of react and react-dom which support hooks and @babel/runtime.

Documentation

You can use the standalone component, documented below, or the useImage hook.

useImage():

The useImage hook allows for incorporating react-image's logic in any component. When using the hook, the component can be wrapped in <Suspense> to keep it from rendering until the image is ready. Specify the fallback prop to show a spinner or any other component to the user while the browser is loading. The hook will throw an error if it fails to find any images. You can wrap your component with an Error Boundary to catch this scenario and do/show something.

Example usage:

import React, {Suspense} from 'react'
import {useImage} from 'react-image'

function MyImageComponent() {
  const {src} = useImage({
    srcList: 'https://www.example.com/foo.jpg',
  })

  return <img src={src} />
}

export default function MyComponent() {
  return (
    <Suspense>
      <MyImageComponent />
    </Suspense>
  )
}

useImage API:

  • srcList: a string or array of strings. useImage will try loading these one at a time and returns after the first one is successfully loaded

  • imgPromise: a promise that accepts a url and returns a promise which resolves if the image is successfully loaded or rejects if the image doesn't load. You can inject an alternative implementation for advanced custom behaviour such as logging errors or dealing with servers that return an image with a 404 header

  • useSuspense: boolean. By default, useImage will tell React to suspend rendering until an image is downloaded. Suspense can be disabled by setting this to false.

returns:

  • src: the resolved image address
  • isLoading: the currently loading status. Note: this is never true when using Suspense
  • error: any errors ecountered, if any

Standalone component (legacy)

When possible, you should use the useImage hook. This provides for greater flexibility and provides support for React Suspense.

Include react-image in your component:

import {Img} from 'react-image'

and set a source for the image:

const myComponent = () => <Img src="https://www.example.com/foo.jpg" />

will resolve to:

<img src="https://www.example.com/foo.jpg">

If the image cannot be loaded, <img> will not be rendered, preventing a "broken" image from showing.

Multiple fallback images:

When src is specified as an array, react-image will attempt to load all the images specified in the array, starting at the first and continuing until an image has been successfully loaded.

const myComponent = () => (
  <Img
    src={['https://www.example.com/foo.jpg', 'https://www.example.com/bar.jpg']}
  />
)

If an image has previously been attempted unsuccessfully, react-image will not retry loading it again until the page is reloaded.

Show a "spinner" or other element before the image is loaded:

const myComponent = () => (
  <Img
    src={['https://www.example.com/foo.jpg', 'https://www.example.com/bar.jpg']}
    loader={/*any valid react element */}
  />
)

If an image was previously loaded successfully (since the last time the page was loaded), the loader will not be shown and the image will be rendered immediately instead.

Show a fallback element if none of the images could be loaded:

const myComponent = () => (
  <Img
    src={['https://www.example.com/foo.jpg', 'https://www.example.com/bar.jpg']}
    unloader={/*any valid react element */}
  />
)

NOTE:

The following options only apply to the <Img> component, not to the useImage hook. When using the hook you can inject a custom image resolver with custom behaviour as required.

Decode before paint

By default and when supported by the browser, react-image uses Image.decode() to decode the image and only render it when it's fully ready to be painted. While this doesn't matter much for vector images (such as svg's) which are rendered immediately, decoding the image before painting prevents the browser from hanging or flashing while the image is decoded. If this behaviour is undesirable, it can be disabled by setting the decode prop to false:

const myComponent = () => (
  <Img src={'https://www.example.com/foo.jpg'} decode={false} />
)

Loading images with a CORS policy

When loading images from another domain with a CORS policy, you may find you need to use the crossorigin attribute. For example:

const myComponent = () => (
  <Img src={'https://www.example.com/foo.jpg'} crossorigin="anonymous" />
)

Animations and other advanced uses

A wrapper element container can be used to facilitate higher level operations which are beyond the scope of this project. container takes a single property, children which is whatever is passed in by React Image (i.e. the final <img> or the loaders).

For example, to animate the display of the image (and animate out the loader) a wrapper can be set:

<Img
  src={'https://www.example.com/foo.jpg'}
  container={(children) => {
    return <div className="foo">{children}</div>
  }}
/>

The <img> will now be contained by the div with class foo which can be targeted via css. A crude example of a transition using ReactCSSTransitionReplace can be found here. Error reporting (i.e. logging images that loaded ok or failed to load) can be accomplished with container, too. A sample implementation can be found here.

By default, the loader and unloader components will also be wrapped by the container component. These can be set independently by passing a container via loaderContainer or unloaderContainer. To disable the loader or unloader from being wrapped, pass a noop to loaderContainer or unloaderContainer (like unloaderContainer={img => img}).

Recipes

Delay rendering until element is visible (lazy rendering)

By definition, React Image will try loading images right away. This may be undesirable in some situations, such as when the page has many images. As with any react element, rendering can be delayed until the image is actually visible in the viewport using popular libraries such as react-visibility-sensor. Here is a quick sample (psudocode/untested!):

import {Img} from 'react-image'
import VisibilitySensor from 'react-visibility-sensor'

const myComponent = () =>
  <VisibilitySensor>
    <Img src='https://www.example.com/foo.jpg'>
  </VisibilitySensor>

Note: it is not necessary to use React Image to prevent loading of images past "the fold" (i.e. not currently visible in the window). Instead just use the native HTML <img> element and the loading="lazy" prop. See more here.

Animate image loading

see above

License

react-image is available under the MIT License

changelog

4.0.3

  • Update peerDependencies in package.json

4.0.2

  • add IE support

4.0.1

  • export types ImgProps/useImageProps

4.0.0

  • BREAKING: all exports are now named exports

3.0.3

  • build hooks for umd

3.0.2

  • dont include typescript libs in build modules
  • include esm modules

3.0.1

  • include missing files

3.0.0

  • move to typescript
  • add useImage hook
  • allow for an image loader to be injected
  • BREAKING: requires react 16.8 or higher

2.4.0

  • fix: TS Interface Error for 'src' attribute. Related to issue: #260

2.3.0

  • fix: typescript declarations

2.2.2

  • add: typescript declarations

    2.2.1

  • fix: Removes warnings of unsafe lifecycle methods from console due to react 16.9 update.

    2.2.0

  • fix:Use correct case for crossOrigin and ensure prop is used both for the initial image fetch and in the final <img> element

    2.1.3

  • fix: nullify callbacks before removing - #237

    2.1.2

  • fix: don't call handlers multiple times, fixes: #236

    2.1.1

  • fix: unset incorrect prop in https://github.com/mbrevda/react-image/pull/223

    2.1.0

  • Add: abort image download on unmount https://github.com/mbrevda/react-image/pull/223

    2.0.0

  • build: move to rollup

  • Fix: Don't return a bool from constructor https://github.com/mbrevda/react-image/pull/220

    1.5.1

  • update babel loader to v7

    1.5.0

  • Add: loaderContainer/unloaderContainer (#208, #211). Thanks @eedrah!

  • Test: test built libs

    1.4.1

  • Fix: strip dev-specific code when compiling

    1.4.0

  • Add: container props

  • Fix: issue deleting src prop in Safari (#87)
  • Add: babel-runtime as peer dep for https://pnpm.js.org/ (#199, #200). Thanks @vjpr!
  • Add: (crude) demo including transitions

    1.3.1

  • bug: Don't pass decode prop to underlying <img>

    1.3.0

  • Use img.decode() by default where available

    1.2.0

  • Add support for React 16

    1.0.1

  • move to new prop-types package

  • add 100% test coverage

    1.0.0

  • Renamed to react-image

    0.6.3

  • Housekeeping: update dependencies

  • Add recipes

    0.6.2

  • Fix Readme formatting

    0.6.1

  • Start iteration at current location

    0.6.0

  • Add a cache so that we don't attempt the same image twice (per page load)

    0.5.0

  • Fix issue where index would overshoot available sources

  • Don't try setting state if this.i was already destroyed, which probably means that we have been unmounted

    0.4.2

  • Remove Browsierfy config

    0.4.1

  • Revert 0.4.0

    0.3.0

  • Don't overshoot sourceList when state.currentIndex

  • Ensure state has been set before trying to load images when new props are delivered

    0.2.0

  • Restart the loading process when src prop changes

    0.1.0

  • Don't use until we know the image can be rendered. This will prevent the "jumping" when loading an image and the preloader is displayed at the same time as the image

    0.0.11

  • Don't require src to be set

    0.0.10

  • Made react a peer depends

    0.0.8

  • Return null instead of false from React component. Thanks @tikotzky!