Tiny (2.3kB) React component for image lazy loading
npm install react-pics --save
or install with Yarn if you prefer:
yarn add react-pics
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 theuse
prop.
import Pic from 'react-pics';
function MyPics() {
return (
<Pic>
<img src="/my-image-high-res.jpg" />
</Pic>
)
}
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>
)
}
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>
)
}
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>
)
}
string | Element<any>
| Optional | Default:"picture"
Replaces the default <picture>
component with something else.
function MyPics() {
return (
<Pic use="div">
<img src="/my-image-high-res.jpg" />
</Pic>
)
}
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>
)
}