🎁 Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Adding a background image to a NextJS app

Let’s see how we can add a background image for all the pages in a NextJs application.

By the end of this example, we will build the below NextJs app layout:Adding a background image to a NextJS app

Note that we will just NextJs version 13+.

We will start from the default output of the create-next-app utility.

First, we will create a AppBgImg.js component that will serve as the main renderer of the background image:

// src/app/AppBgImg.js

import Image from "next/image";
import bgImage from 'public/bg.webp';

export default function AppBgImg() {
  return <Image 
    src={bgImage}
    placeholder="blur"
    fill
    sizes="100vw"
    style={{
      objectFit: 'cover',
      zIndex: -1
    }}
  />
}

A few things to note here:

  • given that we are using the NextJs image component we will have optimization out of the box. This can be useful, given that some background images can be quite big.
  • the fill attribute was added in NextJs 13 and specifies that the image should take the full width and height of the parent, without us needing to set manual values. Before this was done with the layout attribute.
  • we are importing the background image from the public folder, but we can also external images. Just be sure to add the external image url to the next.config.js file in order to prevent the invalid src prop, hostname is not configured error
  • the zIndex: -1 will make sure that the background image will not overlap the main stacking context of the pages

Having created the AppBgImg component we can now use it in the src/app/layout.js file:

// src/app/layout.js

export default function RootLayout({ children }) {
 return (
  <html lang="en">
   <body>
    <AppBgImg/>
    {children}
   </body>
  </html>
 )
}

Given that this is the main layout file of the app, it will get automatically be applied to all the pages.

And this is it! That's all that we need to apply a background image to a NextJs app. You can see the full code in my GitHub repo.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

πŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

Your email address will not be published. Required fields are marked *