Skip to content

Instantly share code, notes, and snippets.

@Accudio
Created September 25, 2021 21:30
Show Gist options
  • Save Accudio/1250f383ca0a084d58ce923d1ae18eee to your computer and use it in GitHub Desktop.
Save Accudio/1250f383ca0a084d58ce923d1ae18eee to your computer and use it in GitHub Desktop.
Example React component abstraction of an Image CDN. Built with CloudImage and an alias in mind, customise as your setup and provider.
import Image from '../components/Image'
export default function () {
return (
<Image
src="otter.jpg"
alt="an otter standing on a log looking majestic"
srcset={[300, 450, 600, 800, 1000, 1200]}
sizes="100vw"
width="1200"
height="800"
loading="lazy"
className="image-class mb-xl"
/>
)
}
import { useEffect, useState } from "react";
const CDN_BASE = "https://example.imagecdn.com";
const defaults = {
alt: "",
srcset: [300, 450, 600, 800, 1000, 1200],
sizes: "(min-width: 82rem) 80rem, calc(100vw - 2rem)",
loading: "lazy",
className: false,
picClassName: false,
lowdpiQuality: 80,
hidpiQuality: 40
};
const Image = (props) => {
const [fallback, setFallback] = useState("");
const [srcset, setSrcset] = useState("");
const [hidpiSrcset, setHidpiSrcset] = useState("");
useEffect(() => {
const path = `/cdn/${props.src}`;
const lowdpiQuality = props.lowdpiQuality || defaults.lowdpiQuality;
const hidpiQuality = props.hidpiQuality || defaults.hidpiQuality;
const lastWidth = props.srcset[props.srcset.length - 1];
setFallback(createSrc(path, lastWidth, lowdpiQuality));
setSrcset(createSrcset(path, props.srcset, lowdpiQuality));
setHidpiSrcset(createSrcset(path, props.srcset, hidpiQuality));
}, [props.src, props.srcset, props.lowdpiQuality, props.hidpiQuality]);
return (
<pre>
<picture className={props.picClassName || defaults.picClassName}>
<source
media="(-webkit-min-device-pixel-ratio: 1.5)"
srcset={hidpiSrcset}
sizes={props.sizes || defaults.sizes}
/>
<img
className={props.className || defaults.className}
alt={props.alt || defaults.alt}
src={fallback}
srcset={srcset}
sizes={props.sizes || defaults.sizes}
width={props.width}
height={props.height}
loading={props.loading || defaults.loading}
decoding="async"
/>
</picture>
</pre>
);
};
// customise this function depending on your image CDN and setup
function createSrc(path, width, quality) {
return `${CDN_BASE}${path}?w=${width}&q=${quality}`;
}
function createSrcset(path, widths, quality) {
const srcsetArr = widths.map((width) => {
const url = createSrc(path, width, quality);
return `${url} ${width}w`;
});
return srcsetArr.join(",");
}
export default Image;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment