React Pics

Tiny (2.3kB) React component for image lazy loading.

Installation

npm install react-pics --save

or install with Yarn if you prefer:

yarn add react-pics

Usage

Basic

Place your image component as a child to <Pic> and it will handle the lazy loading for you.

Note: by default, <Pic> renders a <picture> component. To change this, you can add a custom component with the use prop.

import Pic from 'react-pics';

function MyPics() {
  return (
    <Pic>
      <img src="/my-image-high-res.jpg" />
    </Pic>
  )
}

With a placeholder

Give the placeholder component your image:

import Pic from 'react-pics';

function MyPics() {
  return (
    <Pic placeholder={<img src="/my-image-low-res.jpg" />}>
      <img src="/my-image-high-res.jpg" />
    </Pic>
  )
}

Responsive images

The <Pics> inherits the nature of the <picture> component. You can render different images for certain viewports using the <source> component.

import Pic from 'react-pics';

function MyPics() {
  return (
    <Pic placeholder={<img src="/my-image-low-res.jpg" />}>
      <source media="(max-width: 480px)" src="/my-image-480w.jpg" />
      <source media="(max-width: 720px)" src="/my-image-720w.jpg" />
      <source media="(max-width: 1024px)" src="/my-image-1024w.jpg" />
      <img src="/my-image-high-res.jpg" />
    </Pic>
  )
}

Props on <Pic>

You can add HTML props to <Pic> if you wish:

import Pic from 'react-pics';

function MyPics() {
  return (
    <Pic style={{ width: '100%' }}>
      <img src="/my-image-high-res.jpg" />
    </Pic>
  )
}
import Pic from 'react-pics';
import styled from 'styled-components';

const AwesomePic = styled(Pic)`
  height: 100%
`;

function MyPics() {
  return (
    <AwesomePic>
      <img src="/my-image-high-res.jpg" />
    </AwesomePic>
  )
}

<Pic> props

use

string | Element<any> | Optional | Default: "picture"

Replaces the default <picture> component with something else.

Example

function MyPics() {
  return (
    <Pic use="div">
      <img src="/my-image-high-res.jpg" />
    </Pic>
  )
}

placeholder

Element<"img"> | Optional

Add a placeholder image to use while the image loads.

import Pic from 'react-pics';

function MyPics() {
  return (
    <Pic placeholder={<img src="/my-image-low-res.jpg" />}>
      <img src="/my-image-high-res.jpg" />
    </Pic>
  )
}

GitHub