Generate the sizes attribute for HTML img and picture tags.
npm install @renditions/get-sizes
import getSizes from '@renditions/get-sizes'
const sizes = getSizes({
size: '100vw',
breakpoints: [
{
mediaMinWidth: '960px',
size: '50vw'
},
{
mediaMinWidth: '480px'
}
]
})
console.log({ sizes })
// { sizes: '(min-width: 960px) 50vw,(min-width: 480px) 100vw,100vw' }
The breapoints argument is expected to be an array sorted by mediaMinWidth
in descending order.
To sort the breakpoints automatically, pass true
for the second argument:
const sizesConfig = {
size: '100vw',
breakpoints: [
{
mediaMinWidth: '960px',
size: '50vw'
},
{
mediaMinWidth: '1440px',
size: '33vw'
},
{
mediaMinWidth: '480px'
}
]
}
const sizes = getSizes(sizesConfig, true)
console.log({ sizes })
// { sizes: '(min-width: 1440px) 33vw,(min-width: 960px) 50vw,(min-width: 480px) 100vw,100vw' }
The breakpoints array can be also be omitted entirely:
console.log({ sizes: getSizes({ size: '100vw' }) })
// { sizes: '100vw' }
import React from 'react'
import getSizes from '@renditions/get-sizes'
const MyImage = ({ size = '100vw', ...rest }) => {
const sizes = getSizes({ size })
return <img sizes={sizes} {...rest} />
}