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

Is it possible for me to utilize this code for logging in through a dialog box?

Here is the code snippet I have on the client side: <p>Username:</p> <p><asp:TextBox ID="tbUsername" runat="server"></asp:TextBox></p> <p>Password:</p> <p><asp:TextBox ID="tbPassword" runat="server ...

The dropdown feature within a bootstrap button group is malfunctioning

As part of the web track in cs50, I am working on creating a webpage. My goal is to include options for navigating to the next or previous pages, as well as a dropdown menu with all the pages in between. However, when using Bootstrap's code, the dropd ...

A guide to implementing infinite scrolling with vue-infinite-loading in Nuxt.js (Vue.js)

Currently, I am working on developing a web application using Nuxt.js (Vue.js). Initially, to set up the project, I used the command: vue init nuxt/express MyProject ~page/help.vue <template> <div> <p v-for="item in list"> ...

Developing an HTML table with the power of JavaScript and JSON

I am having difficulty creating an HTML table using JavaScript with JSON input. In my code, I'm using a placeholder in the HTML that will be filled by a innerHTML call in Javascript: for (var i = 0; i < json.data.length; i++) { listItem = json. ...

The styling applied through the MUI TextField sx props does not take effect

Currently, I am attempting to customize a TextField component in a unique way using the sx prop: <TextField size="small" sx={{ padding: '1px 3px', fontSize: '0.875rem', lineHeight: '1.25 ...

Utilizing Bootstrap Classes in ReactJS: A Comprehensive Guide

Is it possible to incorporate Bootstrap classes in a React application without actually installing the framework? If so, how can this be achieved and utilized effectively? I would greatly appreciate your assistance with this matter. ...

Is there a way for me to retrieve the header values of a table when I click on a cell?

I have a project where I am developing an application for booking rooms using Angular 2. One of the requirements is to be able to select a cell in a table and retrieve the values of the vertical and horizontal headers, such as "Room 1" and "9:00". The data ...

Incorporate a feature to activate menu upon hovering and deactivate menu when user moves cursor away in React

Recently, I delved into experimenting with react. Currently, my focus is on creating a navBar using material-ui and react. Whenever I hover over the menu, the drop-down appears. However, to close the drop-down, I am required to click outside of it. My goal ...

Sharing variables between different routes in ExpressJS

Currently, I am utilizing ExpressJs with Node.js and have organized all my routes in a 'routes' folder. When setting up the server, my process involves establishing a DB connection followed by defining the routes as shown below: var routes = re ...

Clicking on an element in React Material UI Autocomplete will bring it

I'm currently working with a material-ui autocomplete element <Autocomplete id="combo-box-demo" autoHighlight openOnFocus autoComplete options={this.state.products} getOptionLabel={option => option.productName} style={{ width: 300 ...

Why can't we use percentages to change the max-height property in JavaScript?

I am currently working on creating a responsive menu featuring a hamburger icon. My goal is to have the menu list slide in and out without using jQuery, but instead relying purely on JavaScript. HTML : <div id="animation"> </div> <button ...

Increased height of iPad screen in landscape mode with no body content displayed (iOS7)

The issue: An unusual problem occurs when the specified URL is loaded on an iOS7 iPad in landscape mode; a vertical scrollbar appears. There is absolutely no content within the body, and it seems to be adjusting the body/html margin/padding. It should be ...

What causes delayed state updates in React/NextJS until another state is updated or a fast refresh occurs?

UPDATE: Version 13.3.0 is coming soon! In my code, I have a state variable named localArray that I need to update at a specific index. To achieve this, I decided to create a temporary array to make modifications and then set the state with the updated val ...

React: Trying to use the map function on an empty array will result in an error

I am currently facing an issue while trying to populate a shopping cart with items. Even though I have initialized the cart as an empty array, I keep encountering the following error: TypeError: cart.map is not a function ProductContext.js:34 addItemToCar ...

Effortlessly Transition to Full Screen with Div Expansion on Click

I'm currently working on creating a smooth transition for a div to expand fullscreen when clicked. My goal is to achieve a similar effect as the case studies on this website: Although my code can make the div go fullscreen, there's an issue with ...

Stealthy Material UI continuing to display components

I am facing a challenge with selectively hiding a material ui component. Initially, my idea was to simply not render the element at all rather than just hiding it based on 'breakpoint' reasons. However, as per the documentation for the mateiral ...

I am attempting to arrange 9 images in a grid format of 3 rows by 3 columns to create a seamless

I am currently working on setting up a 3x3 grid on my website with 9 images and text underneath. The first 6 images are displaying as I intended, but when I add the last 3 images, the layout gets messed up. The first image jumps under the 3rd image on the ...

Obtain an array from an Ajax request using jQuery Datatables

I have integrated the jQuery DataTables Select plugin into my project to enable the selection of multiple rows from a table and storing their data inside an array. Subsequently, I am attempting to make an Ajax Request to pass this array to another PHP file ...

Utilizing data from an external JavaScript file in an Express application

I am currently developing an application using Node.js Express, where I need to pass some data from Express and utilize it in an external JavaScript file. Below is my app.js: const express=require('express'); const path=require('path&apos ...

The hyperlink tag within the overlay div is unresponsive

I'm facing an issue with my overlay div (rb-overlay) that pops up when users click on a page option. The overlay takes up the entire page and includes a close button in the top right corner. However, I've noticed that the link at the end of the t ...