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!