Skip to content

Commit b89845a

Browse files
authored
[material-ui][Avatar] Fix slotProps.img not spread to hook (#44536)
1 parent cdb03a5 commit b89845a

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

packages/mui-material/src/Avatar/Avatar.js

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -163,17 +163,23 @@ const Avatar = React.forwardRef(function Avatar(inProps, ref) {
163163

164164
let children = null;
165165

166-
// Use a hook instead of onError on the img element to support server-side rendering.
167-
const loaded = useLoaded({ ...imgProps, src, srcSet });
168-
const hasImg = src || srcSet;
169-
const hasImgNotFailing = hasImg && loaded !== 'error';
170-
171166
const ownerState = {
172167
...props,
173-
colorDefault: !hasImgNotFailing,
174168
component,
175169
variant,
176170
};
171+
172+
// Use a hook instead of onError on the img element to support server-side rendering.
173+
const loaded = useLoaded({
174+
...imgProps,
175+
...(typeof slotProps.img === 'function' ? slotProps.img(ownerState) : slotProps.img),
176+
src,
177+
srcSet,
178+
});
179+
const hasImg = src || srcSet;
180+
const hasImgNotFailing = hasImg && loaded !== 'error';
181+
182+
ownerState.colorDefault = !hasImgNotFailing;
177183
// This issue explains why this is required: https://github.com/mui/material-ui/issues/42184
178184
delete ownerState.ownerState;
179185

packages/mui-material/src/Avatar/Avatar.test.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,20 @@ describe('<Avatar />', () => {
6262
fireEvent.error(img);
6363
expect(onError.callCount).to.equal(1);
6464
});
65+
66+
it('should pass slots.img to `useLoaded` hook', () => {
67+
const originalImage = global.Image;
68+
const image = {};
69+
global.Image = function Image() {
70+
return image;
71+
};
72+
73+
render(<Avatar src="/fake.png" slotProps={{ img: { crossOrigin: 'anonymous' } }} />);
74+
75+
expect(image.crossOrigin).to.equal('anonymous');
76+
77+
global.Image = originalImage;
78+
});
6579
});
6680

6781
describe('image avatar with unrendered children', () => {

0 commit comments

Comments
 (0)