@renditions/get-srcset
TypeScript icon, indicating that this package has built-in type declarations

1.1.3 • Public • Published

@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} />
}

Package Sidebar

Install

npm i @renditions/get-srcset

Weekly Downloads

10

Version

1.1.3

License

Apache-2.0

Unpacked Size

16.9 kB

Total Files

7

Last publish

Collaborators

  • srilq