Skip to content

Commit 7eca299

Browse files
fix(react-avatar): Do not render the image when src prop is undefined (#28146)
* fix: Do not render the image when src prop is undefined. * change file * typo in change file * requested changes
1 parent 16a2631 commit 7eca299

3 files changed

Lines changed: 19 additions & 1 deletion

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"type": "patch",
3+
"comment": "fix: Do not render the image when src prop is undefined.",
4+
"packageName": "@fluentui/react-avatar",
5+
"email": "[email protected]",
6+
"dependentChangeType": "patch"
7+
}

packages/react-components/react-avatar/src/components/Avatar/Avatar.test.tsx

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,4 +247,10 @@ describe('Avatar', () => {
247247
expect(root.getAttribute('aria-label')).toBe('First Last');
248248
expect(root.getAttribute('aria-labelledby')).toBeFalsy();
249249
});
250+
251+
it('does not render an image when the src attribute is undefined', () => {
252+
render(<Avatar image={{ src: undefined, alt: 'test-image' }} />);
253+
254+
expect(screen.queryByAltText('test-image')).toBeNull();
255+
});
250256
});

packages/react-components/react-avatar/src/components/Avatar/useAvatar.tsx

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ export const useAvatar_unstable = (props: AvatarProps, ref: React.Ref<HTMLElemen
4545
);
4646

4747
const [imageHidden, setImageHidden] = React.useState<true | undefined>(undefined);
48-
const image: AvatarState['image'] = resolveShorthand(props.image, {
48+
let image: AvatarState['image'] = resolveShorthand(props.image, {
4949
defaultProps: {
5050
alt: '',
5151
role: 'presentation',
@@ -54,6 +54,11 @@ export const useAvatar_unstable = (props: AvatarProps, ref: React.Ref<HTMLElemen
5454
},
5555
});
5656

57+
// Image shouldn't be rendered if its src is not set
58+
if (!image?.src) {
59+
image = undefined;
60+
}
61+
5762
// Hide the image if it fails to load and restore it on a successful load
5863
if (image) {
5964
image.onError = mergeCallbacks(image.onError, () => setImageHidden(true));

0 commit comments

Comments
 (0)