Skip to content

Commit

Permalink
[material-ui][Avatar] Fix slotProps.img not spread to hook (#44536)
Browse files Browse the repository at this point in the history
  • Loading branch information
siriwatknp authored Nov 28, 2024
1 parent cdb03a5 commit b89845a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 6 deletions.
18 changes: 12 additions & 6 deletions packages/mui-material/src/Avatar/Avatar.js
Original file line number Diff line number Diff line change
Expand Up @@ -163,17 +163,23 @@ const Avatar = React.forwardRef(function Avatar(inProps, ref) {

let children = null;

// Use a hook instead of onError on the img element to support server-side rendering.
const loaded = useLoaded({ ...imgProps, src, srcSet });
const hasImg = src || srcSet;
const hasImgNotFailing = hasImg && loaded !== 'error';

const ownerState = {
...props,
colorDefault: !hasImgNotFailing,
component,
variant,
};

// Use a hook instead of onError on the img element to support server-side rendering.
const loaded = useLoaded({
...imgProps,
...(typeof slotProps.img === 'function' ? slotProps.img(ownerState) : slotProps.img),
src,
srcSet,
});
const hasImg = src || srcSet;
const hasImgNotFailing = hasImg && loaded !== 'error';

ownerState.colorDefault = !hasImgNotFailing;
// This issue explains why this is required: https://github.com/mui/material-ui/issues/42184
delete ownerState.ownerState;

Expand Down
14 changes: 14 additions & 0 deletions packages/mui-material/src/Avatar/Avatar.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,20 @@ describe('<Avatar />', () => {
fireEvent.error(img);
expect(onError.callCount).to.equal(1);
});

it('should pass slots.img to `useLoaded` hook', () => {
const originalImage = global.Image;
const image = {};
global.Image = function Image() {
return image;
};

render(<Avatar src="/fake.png" slotProps={{ img: { crossOrigin: 'anonymous' } }} />);

expect(image.crossOrigin).to.equal('anonymous');

global.Image = originalImage;
});
});

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

0 comments on commit b89845a

Please sign in to comment.