fix(image): override default auto height (#3327)

* fix(image): override default auto height

* feat(changeset): add changeset

* feat(image): add test

* refactor(image): add comment
This commit is contained in:
աӄա 2024-07-06 15:54:01 +08:00 committed by GitHub
parent 1671f569ea
commit 57f7c9555e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 38 additions and 0 deletions

View File

@ -0,0 +1,5 @@
---
"@nextui-org/image": patch
---
override default auto height (#3325)

View File

@ -73,4 +73,24 @@ describe("Image", () => {
expect(wrapper.getByRole("img")).toHaveAttribute("src", src);
expect(onLoad).toHaveBeenCalled();
});
test("should disable aspect ratio if height is set", () => {
const wrapper = render(
<>
<Image height={30} src={src} />
<Image height={"40px"} src={src} />
<Image height={50} src={src} width={50} />
<Image height={"60px"} src={src} width={50} />
</>,
);
const images = wrapper.getAllByRole("img");
expect(images).toHaveLength(4);
expect(getComputedStyle(images[0]).height).toBe("30px");
expect(getComputedStyle(images[1]).height).toBe("40px");
expect(getComputedStyle(images[2]).height).toBe("50px");
expect(getComputedStyle(images[3]).height).toBe("60px");
});
});

View File

@ -96,6 +96,7 @@ export function useImage(originalProps: UseImageProps) {
srcSet,
sizes,
crossOrigin,
height,
...otherProps
} = props;
@ -131,6 +132,11 @@ export function useImage(originalProps: UseImageProps) {
};
}, [props?.width]);
const h = useMemo(
() => (height ? (typeof height === "number" ? `${height}px` : height) : "auto"),
[height],
);
const showFallback = (!src || !isImgLoaded) && !!fallbackSrc;
const showSkeleton = isLoading && !disableSkeleton;
@ -159,6 +165,13 @@ export function useImage(originalProps: UseImageProps) {
sizes,
crossOrigin,
...otherProps,
style: {
// img has `height: auto` by default
// passing the custom height here to override if it is specified
...(height && {height: h}),
...props.style,
...otherProps.style,
},
};
};