From d8d57d489b3285848ce5bb5c73ed6369c25ce9cf Mon Sep 17 00:00:00 2001 From: Valentin Palkovic Date: Wed, 1 Nov 2023 10:18:49 +0100 Subject: [PATCH] Next.js: Fix forwarding ref for Image component --- .../nextjs/src/images/next-image.tsx | 19 +++++++++++++++---- .../nextjs/template/stories/Image.stories.jsx | 15 ++++++++++++++- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/code/frameworks/nextjs/src/images/next-image.tsx b/code/frameworks/nextjs/src/images/next-image.tsx index 8fc964785f6b..f2e2d9d1467c 100644 --- a/code/frameworks/nextjs/src/images/next-image.tsx +++ b/code/frameworks/nextjs/src/images/next-image.tsx @@ -13,10 +13,21 @@ import { defaultLoader } from './next-image-default-loader'; const ImageContext = ImageContextValue as typeof ImageContextType; -const MockedNextImage = ({ loader, ...props }: _NextImage.ImageProps) => { - const imageParameters = React.useContext(ImageContext); +const MockedNextImage = React.forwardRef( + ({ loader, ...props }, ref) => { + const imageParameters = React.useContext(ImageContext); - return ; -}; + return ( + + ); + } +); + +MockedNextImage.displayName = 'NextImage'; export default MockedNextImage; diff --git a/code/frameworks/nextjs/template/stories/Image.stories.jsx b/code/frameworks/nextjs/template/stories/Image.stories.jsx index 7a8803a6e992..dfb9894e972c 100644 --- a/code/frameworks/nextjs/template/stories/Image.stories.jsx +++ b/code/frameworks/nextjs/template/stories/Image.stories.jsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useRef, useState } from 'react'; import Image from 'next/image'; import { waitFor } from '@storybook/testing-library'; @@ -81,3 +81,16 @@ export const Eager = { }, }, }; + +export const WithRef = { + render() { + const [ref, setRef] = useState(null); + + return ( +
+ Accessibility +

Alt attribute of image: {ref?.alt}

+
+ ); + }, +};