Unverified Commit c4b6bb85 authored by Jan Kaifer's avatar Jan Kaifer Committed by GitHub

Add `ref` forwarding for `next/image` (#43193)

Add ref forwarding for next/image with integration test


- fixes https://github.com/vercel/next.js/discussions/42885
- fixes https://github.com/vercel/next.js/issues/18398 (this one was closed with `onLoadingComplete`)

## Feature

- [x] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Documentation added
Co-authored-by: 's avatarSteven <229881+styfle@users.noreply.github.com>
parent 0f195f02
...@@ -16,6 +16,7 @@ description: Enable Image Optimization with the built-in Image component. ...@@ -16,6 +16,7 @@ description: Enable Image Optimization with the built-in Image component.
| Version | Changes | | Version | Changes |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `v13.0.6` | `ref` prop added. |
| `v13.0.0` | `<span>` wrapper removed. `layout`, `objectFit`, `objectPosition`, `lazyBoundary`, `lazyRoot` props removed. `alt` is required. `onLoadingComplete` receives reference to `img` element. Built-in loader config removed. | | `v13.0.0` | `<span>` wrapper removed. `layout`, `objectFit`, `objectPosition`, `lazyBoundary`, `lazyRoot` props removed. `alt` is required. `onLoadingComplete` receives reference to `img` element. Built-in loader config removed. |
| `v12.3.0` | `remotePatterns` and `unoptimized` configuration is stable. | | `v12.3.0` | `remotePatterns` and `unoptimized` configuration is stable. |
| `v12.2.0` | Experimental `remotePatterns` and experimental `unoptimized` configuration added. `layout="raw"` removed. | | `v12.2.0` | Experimental `remotePatterns` and experimental `unoptimized` configuration added. `layout="raw"` removed. |
...@@ -284,7 +285,6 @@ Other properties on the `<Image />` component will be passed to the underlying ...@@ -284,7 +285,6 @@ Other properties on the `<Image />` component will be passed to the underlying
`img` element with the exception of the following: `img` element with the exception of the following:
- `srcSet`. Use [Device Sizes](#device-sizes) instead. - `srcSet`. Use [Device Sizes](#device-sizes) instead.
- `ref`. Use [`onLoadingComplete`](#onloadingcomplete) instead.
- `decoding`. It is always `"async"`. - `decoding`. It is always `"async"`.
## Configuration Options ## Configuration Options
......
...@@ -7,6 +7,7 @@ import React, { ...@@ -7,6 +7,7 @@ import React, {
useContext, useContext,
useMemo, useMemo,
useState, useState,
forwardRef,
} from 'react' } from 'react'
import Head from '../shared/lib/head' import Head from '../shared/lib/head'
import { getImageBlurSvg } from '../shared/lib/image-blur-svg' import { getImageBlurSvg } from '../shared/lib/image-blur-svg'
...@@ -362,7 +363,9 @@ function handleLoading( ...@@ -362,7 +363,9 @@ function handleLoading(
}) })
} }
const ImageElement = ({ const ImageElement = forwardRef<HTMLImageElement | null, ImageElementProps>(
(
{
imgAttributes, imgAttributes,
heightInt, heightInt,
widthInt, widthInt,
...@@ -385,7 +388,9 @@ const ImageElement = ({ ...@@ -385,7 +388,9 @@ const ImageElement = ({
onLoad, onLoad,
onError, onError,
...rest ...rest
}: ImageElementProps) => { },
forwardedRef
) => {
loading = isLazy ? 'lazy' : loading loading = isLazy ? 'lazy' : loading
return ( return (
<> <>
...@@ -402,6 +407,13 @@ const ImageElement = ({ ...@@ -402,6 +407,13 @@ const ImageElement = ({
style={{ ...imgStyle, ...blurStyle }} style={{ ...imgStyle, ...blurStyle }}
ref={useCallback( ref={useCallback(
(img: ImgElementWithDataProp | null) => { (img: ImgElementWithDataProp | null) => {
if (forwardedRef) {
if (typeof forwardedRef === 'function') forwardedRef(img)
else if (typeof forwardedRef === 'object') {
// @ts-ignore - .current is read only it's usually assigned by react internally
forwardedRef.current = img
}
}
if (!img) { if (!img) {
return return
} }
...@@ -414,7 +426,10 @@ const ImageElement = ({ ...@@ -414,7 +426,10 @@ const ImageElement = ({
} }
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
if (!srcString) { if (!srcString) {
console.error(`Image is missing required "src" property:`, img) console.error(
`Image is missing required "src" property:`,
img
)
} }
if (img.getAttribute('alt') === null) { if (img.getAttribute('alt') === null) {
console.error( console.error(
...@@ -442,6 +457,7 @@ const ImageElement = ({ ...@@ -442,6 +457,7 @@ const ImageElement = ({
setBlurComplete, setBlurComplete,
onError, onError,
unoptimized, unoptimized,
forwardedRef,
] ]
)} )}
onLoad={(event) => { onLoad={(event) => {
...@@ -470,9 +486,12 @@ const ImageElement = ({ ...@@ -470,9 +486,12 @@ const ImageElement = ({
/> />
</> </>
) )
} }
)
export default function Image({ const Image = forwardRef<HTMLImageElement | null, ImageProps>(
(
{
src, src,
sizes, sizes,
unoptimized = false, unoptimized = false,
...@@ -494,7 +513,9 @@ export default function Image({ ...@@ -494,7 +513,9 @@ export default function Image({
lazyBoundary, lazyBoundary,
lazyRoot, lazyRoot,
...all ...all
}: ImageProps) { },
forwardedRef
) => {
const configContext = useContext(ImageConfigContext) const configContext = useContext(ImageConfigContext)
const config: ImageConfig = useMemo(() => { const config: ImageConfig = useMemo(() => {
const c = configEnv || configContext || imageConfigDefault const c = configEnv || configContext || imageConfigDefault
...@@ -532,7 +553,8 @@ export default function Image({ ...@@ -532,7 +553,8 @@ export default function Image({
if (layout === 'fill') { if (layout === 'fill') {
fill = true fill = true
} }
const layoutToStyle: Record<string, Record<string, string> | undefined> = { const layoutToStyle: Record<string, Record<string, string> | undefined> =
{
intrinsic: { maxWidth: '100%', height: 'auto' }, intrinsic: { maxWidth: '100%', height: 'auto' },
responsive: { width: '100%', height: 'auto' }, responsive: { width: '100%', height: 'auto' },
} }
...@@ -889,7 +911,7 @@ export default function Image({ ...@@ -889,7 +911,7 @@ export default function Image({
} }
return ( return (
<> <>
{<ImageElement {...imgElementArgs} />} {<ImageElement {...imgElementArgs} ref={forwardedRef} />}
{priority ? ( {priority ? (
// Note how we omit the `href` attribute, as it would only be relevant // Note how we omit the `href` attribute, as it would only be relevant
// for browsers that do not support `imagesrcset`, and in those cases // for browsers that do not support `imagesrcset`, and in those cases
...@@ -913,4 +935,7 @@ export default function Image({ ...@@ -913,4 +935,7 @@ export default function Image({
) : null} ) : null}
</> </>
) )
} }
)
export default Image
import React, { useState } from 'react'
import Image from 'next/image'
import { motion } from 'framer-motion'
import testPng from '../images/test.png'
const CustomImage = React.forwardRef((props, ref) => (
<Image
ref={ref}
id="img"
src={testPng}
width={300}
height={300}
alt="test img"
{...props}
/>
))
const MotionImage = motion(CustomImage)
export default function Page() {
const [clicked, setClicked] = useState(false)
return (
<MotionImage
onClick={() => setClicked(true)}
initial={{ opacity: 1 }}
animate={{ opacity: clicked ? 0 : 1 }}
transition={{ duration: 0.5 }}
/>
)
}
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { waitFor } from 'next-test-utils'
import path from 'path'
import webdriver from 'next-webdriver'
describe('next-image-forward-ref', () => {
let next: NextInstance
const appDir = path.join(__dirname, 'app')
beforeAll(async () => {
next = await createNext({
files: new FileRef(appDir),
dependencies: {
'framer-motion': '7.6.9',
},
})
})
afterAll(() => next.destroy())
it('allows framer-motion to animate opacity', async () => {
const browser = await webdriver(next.url, '/framer-motion')
expect(
Number(await browser.elementById('img').getComputedCss('opacity'))
).toBeCloseTo(1)
browser.elementById('img').click()
await waitFor(1000)
expect(
Number(await browser.elementById('img').getComputedCss('opacity'))
).toBeCloseTo(0)
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment