In the old days, when we wanted a hero image that would fill an entire responsive div element, we would use the
background-image, background-size, etc... CSS tags to place our hero image behind the hero foreground. And for years this worked great!
That is... until
srcset images and converts them to
So that's all well and good, but here's the problem: next-image does not work with CSS-defined background images. 😱 But no worries! By using next-image in conjunction with a little Tailwind CSS, we can create a modern hero component that is fully responsive, image-optimized and relatively future-proof... well, at least for the next week or two. 🤣
This tutorial focuses on creating the hero component and is part of a larger series on how to build a complete website using NextJS 13 (yet to be published). You can clone this project as it currently stands here. That being said, I will not be covering the basics of how to create a new NextJS 13 app.
Installing Tailwind CSS
If you don't already have Tailwind CSS in your app, let's get it installed:
This installs our dependencies and initializes our config files. It also installs
react-cool-dimensions, which we will use for shipping properly sized images to the client.
Next, we need to edit a couple of files,
Note that I created some custom utility classes for our theme colors.
Now we want to add the following to the top of our global CSS file, which is usually in
Create a Button Component
We first want to create our child components before we create our higher order component. The only component our hero will have is a button. This example is a nice universal button component that will render either an
<button> element depending on whether or not the
href property is supplied:
Create Our Hero Component
Now we can create our hero component. Don't be alarmed by the complexity, I will explain in full:
So what we have here is an images folder with images we created for our hero based on the viewport's max width, which we detect using the
useDimensions() hook. Every time the viewport width is changed, this hook fires and rounds the new dimension up to the next highest value in our array of dimensions using the custom
arrayCeil() function. This allows us to serve properly sized and cropped images for our hero.
Here is the code for
npm run dev your app and hopefully you see this:
And here's the mobile phone view:
Well, that's all for this tutorial. Be sure to check back soon for my upcoming tutorial: a complete NextJS 13 website! You'll be able to find that and much more at the Designly Blog.