4.1.0 • Published 2 years ago

react-image v4.1.0

Weekly downloads
51,609
License
MIT
Repository
github
Last release
2 years ago

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) and 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 for a version of react and react-dom which support hooks.

Documentation

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

useImage():

The useImage hook allows for incorperating 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 the throw an error if it failes to find any images. You can wrap your componenet with an Error Boundry to catch this scenario and do/show something.

Example usage:

import {useImage} from 'react-image/useImage'

export default function MyComponent() {
  const {src, isLoading, error} = useImage({
    srcList: 'https://www.example.com/foo.jpg',
  })

  return <img src={src} />
}

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 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. This can be disabled by setting this to false.

returns:

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

Standalone component (legacy)

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

Include react-image in your component:

// using an ES6 transpiler, like babel
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 this page was loaded), the loader will not be shown and the image will be rendered directly 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 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 as soon as the <Img> element is rendered in the DOM. 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 (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 nesesary to use React Image to prevent loading of images past "the fold" (i.e. not currently visable on in the window). Instead use the HTML <img> element and the loading="lazy" property. See more here.

Animate image loading

see above

Browser Support

react-image does not include an Object.assign polyfill, that may be needed depending on your targeted browsers. You can add it in one of the following ways:

  1. include it in your package: https://www.npmjs.com/package/es6-object-assign

  2. Use Mozilla's polyfill: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill

  3. Include the following code before including react-image:

Object.assign =
  Object.assign ||
  function (r) {
    for (var t = 1; t < arguments.length; t++) {
      var n = arguments[t]
      for (var a in n)
        Object.prototype.hasOwnProperty.call(n, a) && (r[a] = n[a])
    }
    return r
  }

License

react-image is available under the MIT License

cropwise-react-uicropwise-react-ui-kit@catho-private/catho-componentsmirador-biblissimabetterimagespfxspfx-testodge-lib-latestodge-test33odge-test00odge-libxr3-clientuap-ui-componentsapex-react@busy-bee/ui-wwwseek-josh-cp-uichinese-miradorjosh-122oracle-webcomponentsai-client-base@everything-registry/sub-chunk-2560@itoa/fieldsra-miradortamu-miradortest-dependency-modulewex-adminwex-admin-antdrnotion-xreact-w3-componentsreact_notion_personalsupabase-comments-extensionsupabase-comments-xspencerpaulynotionxreact-notion-x-trkreact-notion-x-yogeshreact-notion-xxxreact-notion-yreact-notionerreact-notion-csharpreact-notion-emailreact-notion-xreact-notion-x-customreact-notion-x-dohunreact-notion-x-hkiratreact-notion-x-jreact-notion-x-personalreact-notion-x-pokepayswapkit-providervolans-react-notion-xva-react-notion-x@mobato-ds/reactmetahkg-webmini-tis-commonmiradormirador-videomirador-knaw-huc-mui5givebox-libintelligent-data-platform-feinstant-react-coregrape-ui-reacthackathon-boostgutenberg-printing-pressjosh-111111l-min-componentsmusalleen-react-thememuitomason-blog-backendpioneer-reactnine36-uipixiv.moenickhsine-k5-fieldsreact-emails-components-miscellaneousreact-enterprise-componentsreact-photo-gallery-tsnpm-react-nexus-headernpm-next-nexus-headernpm-my-test-publishnpm-nexus-headernotion-forgereact-akash-uireact-mapfilterspx-privatesite-headerspace-ui-core-frameworku-react-notion-xui-kit-roi4umi-ld-library@antlerengineering/components@antlervc/components@arcteryx/components-order-history@arcteryx/components-cart@availity/spaces@availity/avatar@availity/mui-spaces@adobe/parliament-ui-components@ballerine/backoffice-v2@ballerine/ui@age/quantum@bodhi-project/brilliant-blue@bodhi-project/components
4.1.0

2 years ago

4.0.3

4 years ago

4.0.2

4 years ago

4.0.1

4 years ago

4.0.0

5 years ago

3.0.3

5 years ago

3.0.2

5 years ago

3.0.1

5 years ago

3.0.0

5 years ago

2.4.0

5 years ago

2.3.0

5 years ago

2.2.2

5 years ago

2.2.1

5 years ago

2.2.0

5 years ago

2.1.3

5 years ago

2.1.2

5 years ago

2.1.1

6 years ago

2.1.0

6 years ago

2.0.0

6 years ago

1.5.1

6 years ago

1.5.0

6 years ago

1.4.1

6 years ago

1.4.0

6 years ago

1.3.1

7 years ago

1.3.0

7 years ago

1.2.0

7 years ago

1.0.1

8 years ago

1.0.0

8 years ago

0.1.0

10 years ago

0.0.0

10 years ago