The background image fails to display properly on the server in Next.js

Hello, I'm currently using NextJs and I have a challenge. I want to set a background image on the body element that is rendered server-side. Below you'll find my code snippets:

First, here is my App.js:

import BodyStyle from '@components/Bodystyle';
return (
    <>
      <BodyStyle bgColor={`url("picture-url")`} />
<>);

Next, let's take a look at my BodyStyle.js file:

const BodyStyle = (props) => {
  const { bgColor } =
    props;
  return (
    <Head>
      <style>{`body { background: ${bgColor} no-repeat center center fixed; background-size: cover;`}</style>
    </Head>
  );

The background is successfully applied to the body, but unfortunately not during SSR (Server-Side Rendering).

However, there's an interesting twist: If I manually copy the code from BodyStyles.js and paste it directly into app.js, the background image appears perfectly on the server side.

Here's an example snippet from App.js showing how the background can be added using Next.js:

import Head from 'next/head';

return (
  <Head>
        <style>{`body { background: url(${url}) no-repeat center center fixed; background-size: cover;`}</style>
      </Head> 
);

I have attached screenshots below for reference: Screenshot without background on SSR: https://i.stack.imgur.com/FwhiW.png

Screenshot with the background on SSR: https://i.stack.imgur.com/uP97c.png

If anyone has any insights or solutions to this issue, your help would be greatly appreciated. Thank you!

Answer №1

It seems that the issue lies in setting the background color before any props are available. I suggest using useEffect or adjusting the code as shown below:

const BodyStyle = ({bgColor}) => {

  return (
    <Head>
      <style>{`body { background: ${bgColor} no-repeat center center fixed; background-size: cover;`}</style>
    </Head>
  );

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Insider knowledge within Nextjs client construction

NextJs has a feature where secrets are categorized as client and backend secrets, according to the documentation. It states that if you prepend the variable with NEXT_PUBLIC_, it will be included in the frontend bundle. You can find more information about ...

Tips for optimizing component rendering in React-Redux and preventing unnecessary re-renders

Currently, I am using react-router-redux and have nested connect()ed components. While this setup works fine, the issue arises when my nested components re-render whenever there is a change in state. The problem lies in the fact that the root has 5 childr ...

Player using unexpected options instead of Video.js options

I have created a basic HTML page with a small JavaScript snippet to function as a playlist, and it was working perfectly fine. However, when I integrated Video.js into the mix, an issue arose. Sometimes, upon reopening the page, the player fails to load p ...

Artwork - Circular design disappears without warning

While working on a clock project purely for enjoyment, I noticed that the minute arc disappears from the canvas as soon as a new minute begins. Any idea why this is happening? Check out the clock in action: https://jsfiddle.net/y0bson6f/ HTML <canvas ...

Recursive array generation

Given an array 'featureList', the goal is to create a new array 'newArray' based on a specific ID. For example, for ID 5, the newArray would be ['MotherBoard','Antenna','Receiver'], where Receiver correspon ...

The Next.js server starts up for a moment before abruptly shutting down

When I run next dev, the server starts momentarily and then closes down. > next dev ready - started server on 0.0.0.0:3000, url: http://localhost:3000 and then it shuts off. I'm using Windows and you can see a screenshot of my CLI here I ran this ...

Connect the Vue component to the Vue instance

I am currently working with a Vue component that looks like this: Vue.component('number-input', { props: {}, template: `<textarea class="handsontableInput subtxt area-custom text-center text-bold" v-model="displayValue" @blur="isInput ...

Fetching JSON data from a GET request in Flask-Python is a straightforward process. By utilizing the

Currently, I am utilizing a GET request in my React app to execute a function that is only "printing" data from my Flask API. While I am able to hit the endpoint and receive a response, I am struggling with attaching the JSON data to the response returned ...

The React component is being rendered repeatedly

I am new to React and decided to implement some functionalities to enhance my understanding of the framework. Currently, I am working on a search feature that displays results in a table format. Each row in the table has a delete option, which triggers a p ...

What is the best way to store HTML in a variable as a string?

Imagine if I have a variable: let display_text = "Cats are pawsome!" I aim to show it as such: <div> <b>Cats</b> are pawsome! </div> To be clear, dynamically enclose the word "cats" whenever it shows up. ...

Unexpected activation of Internet Explorer media queries causing display issues

Check out my CSS code below: @media all and (max-width: 500px){ .calendar_head{ height: 120px; line-height: 60px; } } .calendar_head{ width: 100%; font-weight: 700; color: #6a7783; text-align: center; line-heigh ...

Exploring the Power of Nested Routes in React Router v5.0

I'm currently facing a challenge with setting up routing in my react app. My goal is to have a common layout (including header and footer) for specific Auth routes such as /login, sign-up, forgot-password, etc... Additionally, I require another ...

Understanding CSS notation: The significance behind the symbol ">"

On a specific page of my website, the HTML structure is as follows: <html> <head><!-- Standard content with a link to a CSS file --></head> <body> <div id="splash"> <!-- Importan ...

Implementing Event Listeners in Vue 3.0: A Guide to Attaching to the Parent Element

How can I attach an addEventListener to the parent element in Vue 3.x? I discovered that you can access the parent by using this code: import { getCurrentInstance, onMounted } from 'vue' onMounted(() => { console.log(getCurrentInstance() ...

What could be causing the HTML <DATALIST> dropdown to display next to its input rather than below it?

I have an input linked to a datalist, and it's functioning correctly. However, when I initially open the dropdown, the option list appears next to (right of) the input. After entering a few characters to narrow down the list, it then shifts below the ...

The interactive form fields are not functioning as intended due to a dynamic association issue

Issue with Adding Two Dynamic Form Fields Together I need to add two fields at once by clicking a single button, and each field should have a two-dimensional name structure like [0][0] and [0][1] for saving dual values Although I used jQuery to dyn ...

developing a stand-alone job listings feature

Our website features a job postings page that our clients are interested in incorporating into their own websites. This would allow applicants to easily apply for jobs directly on the client's site, with the information being saved in our system. One ...

Load image in browser for future display in case of server disconnection

Incorporating AngularJS with HTML5 Server-Side Events (SSE) has allowed me to continuously update the data displayed on a webpage. One challenge I've encountered is managing the icon that represents the connection state to the server. My approach inv ...

What steps should I take to ensure that the login page functions properly?

Below is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login Pag ...

Repeated function calls are common in Node.js

Having recently ventured into the world of node js, I encountered an issue when trying to use a python call for data retrieval. The process was quite complex and caused delays in execution and response reception by node js. The code snippet provided below ...