Generate the srcset attribute for HTML img and picture tags.
npm install @renditions/get-srcset
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' }
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' }
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} />
}