Skip to content

Commit

Permalink
should render the correct sizes passed when a noscript is rendered (v…
Browse files Browse the repository at this point in the history
…ercel#37161)

## Bug

- [x] Fixes vercel#36807
- [x] Unit tests added

Please review this PR.

As shown in [this Issue](vercel#36807), the noscript element does not render sizes correctly during SSR.
This change adds `noscriptSizes` to the props passed to `ImageElement` to generate the same `sizes` and `srcset` as the normal img tag that is actually rendered in the browser.
  • Loading branch information
dc7290 authored and Schniz committed May 25, 2022
1 parent c216df6 commit 3a68b50
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
5 changes: 4 additions & 1 deletion packages/next/client/image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ type ImageElementProps = Omit<ImageProps, 'src' | 'loader'> & {
setBlurComplete: (b: boolean) => void
setIntersection: (img: HTMLImageElement | null) => void
isVisible: boolean
noscriptSizes: string | undefined
}

function getWidths(
Expand Down Expand Up @@ -830,6 +831,7 @@ export default function Image({
setBlurComplete,
setIntersection,
isVisible,
noscriptSizes: sizes,
...rest,
}
return (
Expand Down Expand Up @@ -910,6 +912,7 @@ const ImageElement = ({
onLoad,
onError,
isVisible,
noscriptSizes,
...rest
}: ImageElementProps) => {
return (
Expand Down Expand Up @@ -982,7 +985,7 @@ const ImageElement = ({
layout,
width: widthInt,
quality: qualityInt,
sizes: imgAttributes.sizes,
sizes: noscriptSizes,
loader,
})}
{...(layout === 'raw'
Expand Down
15 changes: 15 additions & 0 deletions test/unit/image-rendering.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,4 +79,19 @@ describe('Image rendering', () => {
expect($2('noscript').length).toBe(1)
expect($3('noscript').length).toBe(1)
})

it('should render the correct sizes passed when a noscript element is rendered', async () => {
const element = React.createElement(Image, {
src: '/test.png',
width: 100,
height: 100,
sizes: '50vw',
})
const $ = cheerio.load(ReactDOM.renderToString(element))
const noscriptImg = $('noscript img')
expect(noscriptImg.attr('sizes')).toBe('50vw')
expect(noscriptImg.attr('srcset')).toContain(
'/_next/image?url=%2Ftest.png&w=384&q=75 384w'
)
})
})

0 comments on commit 3a68b50

Please sign in to comment.