Skip to content

Commit

Permalink
fix(image): override default auto height (#3327)
Browse files Browse the repository at this point in the history
* fix(image): override default auto height

* feat(changeset): add changeset

* feat(image): add test

* refactor(image): add comment
  • Loading branch information
wingkwong authored Jul 6, 2024
1 parent 1671f56 commit 57f7c95
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/stale-planes-flash.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@nextui-org/image": patch
---

override default auto height (#3325)
20 changes: 20 additions & 0 deletions packages/components/image/__tests__/image.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
});
13 changes: 13 additions & 0 deletions packages/components/image/src/use-image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ export function useImage(originalProps: UseImageProps) {
srcSet,
sizes,
crossOrigin,
height,
...otherProps
} = props;

Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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,
},
};
};

Expand Down

0 comments on commit 57f7c95

Please sign in to comment.