Skip to content

Instantly share code, notes, and snippets.

@joshuabaker
Last active January 4, 2023 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshuabaker/642e48f443ab5996969dfc7137213542 to your computer and use it in GitHub Desktop.
Save joshuabaker/642e48f443ab5996969dfc7137213542 to your computer and use it in GitHub Desktop.
Converts Chakra responsive syntax (array or object) to sizes for use with image elements.
import { useTheme } from "@chakra-ui/react";
import { objectToArrayNotation } from "@chakra-ui/utils";
export default function useChakraResponsiveImageSizes(sizes) {
const theme = useTheme();
const details = theme.__breakpoints.details;
if (!sizes) {
return null;
}
if (typeof sizes === "string") {
return sizes;
}
if (!Array.isArray(sizes)) {
sizes = objectToArrayNotation(sizes);
}
const last = sizes.pop();
return sizes
.map((size, index) =>
size && details[index]
? `(max-width: ${details[index].maxW}) ${size}`
: null
)
.concat([last])
.filter(Boolean)
.join(", ");
}
@joshuabaker
Copy link
Author

Usage

function MyComponent({ sizes, ...props }) {
  return <NextImage sizes={useChakraResponsiveImageSizes(sizes)} {...props} />
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment