Skip to content
This repository has been archived by the owner on Sep 6, 2021. It is now read-only.
/ get-srcset Public archive

Generate the srcset attribute for HTML img and picture tags.

License

Notifications You must be signed in to change notification settings

renditions/get-srcset

Repository files navigation

@renditions/get-srcset

npm version js-standard-style

Generate the srcset attribute for HTML img and picture tags.

Install

npm install @renditions/get-srcset

Usage

import getSrcset from '@renditions/get-srcset'

const srcset = getSrcset([
  {
    src: '/images/320.jpg',
    width: 320
  },
  {
    src: '/images/1024.jpg',
    width: 1024
  }
])

console.log({ srcset })
// { srcset: '/images/320.jpg 320w,/images/1024.jpg 1024w' }

Sorting

The first argument is expected to be an array sorted by width in ascending order.

To sort the array automatically, pass true for the second argument:

const unsortedRenditions = [
  {
    src: '/images/1024.jpg',
    width: 1024
  },
  {
    src: '/images/320.jpg',
    width: 320
  },
  {
    src: '/images/720.jpg',
    width: 720
  }
]

const srcset = getSrcset(unsortedRenditions, true)

console.log({ srcset })
// { srcset: '/images/320.jpg 320w,/images/720.jpg 720w,/images/1024.jpg 1024w' }

Using with React

import React from 'react'
import getSrcset from '@renditions/get-srcset'

const renditionWidths = ['320', '1024']

const Image = ({ filename, ext, ...rest }) => {
  const renditions = renditionWidths.map(width => ({
    width,
    src: `/images/${filename}_${width}.${ext}`
  }))

  const srcset = getSrcset(renditions)

  return <img srcSet={srcset} {...rest} />
}