Using Next/Link with Theme-UI
A tutorial on how to build a custom Link component for Next.js using Theme-UI
Gia Thinh Nguyen
Published on
Next.js comes packed with optimizations, notably with images since version 10 got released. Essentially, instead of images being optimized at build time, they are lazy loaded by default (meaning they are loaded as users scroll through a page).
These optimizations provide some huge benefits, and we definitely want them rolling with
our Theme-UI project. Since next/image
already provides a React component to use, we can
wrap around with an incredibly useful Theme-UI component called the <AspectRatio>
.
As the name aptly implies, this component preserves the aspect ratio of any image it wraps
around through its ratio
prop.
Taking a look at the code, we come up with the following:
And voilà! We have our <Image>
component ready to use. There is no particular
magic behind this component, it actually uses a well-known padding trick to
calculate the appropriate width/height for the image. NextImage
will naturally
takes whatever space is available using the layout
prop with the value of fill
.
Of course, we should also be able to choose a width or height using the component itself if no aspect ratio is passed.
And that's really it, you now have a versatile component to render images at any size.