Linking a background image in the body to a specific state in next.js

My aim is to create a pomodoro timer using Next.js and I'm trying to link the body's background image to a state. However, my code isn't functioning properly.

This is the code I used to update the body style:

import { VscDebugRestart } from "react-icons/vsc";
import { IoMdSettings } from "react-icons/io";
import { AiFillPlayCircle, AiFillPauseCircle } from "react-icons/ai";
import { FaTasks } from "react-icons/fa";
import { Modal } from "@/components";
import { useModal } from "@/components/modal";
import { useEffect } from "react";

const Timer = () => {
    const settingsModal = useModal();
    const tasksModal = useModal();

    // Update
    useEffect(() => {
        document.body.style.background =
            "url('/images/city-3.jpg') no-repeat center center fixed;";
    }, []);

    return (
        <div className="timer">
            <div className="session-options">
                <button className="btn">studying</button>
                <button className="btn">short break</button>
                <button className="btn">long break</button>
            </div>
            <h1 className="time-info">1:30:00</h1>
            <div className="options">
                <AiFillPlayCircle className="btn-icon" />
                {/* <AiFillPauseCircle className="btn-icon" /> */}
                <VscDebugRestart className="btn-icon" />
                <IoMdSettings
                    className="btn-icon"
                    onClick={settingsModal.open}
                />
                <FaTasks className="btn-icon" />
            </div>
            <Modal modal={settingsModal}>settings</Modal>
        </div>
    );
};

export default Timer;

However, the styling isn't being applied and I haven't encountered any failed requests for the image. (I am certain that the image exists) What steps can I take to rectify this? Are there alternative solutions that would ensure the image adjusts to fit the background even when the size changes?

Answer №1

Take out the semicolon from the background string as it is not valid for this CSS style.

document.body.style.background = "url('/images/city-3.jpg') no-repeat center center fixed"

Answer №2

Wow, what a breakthrough! Thanks a bunch for your assistance in troubleshooting. I managed to rectify the issue and implemented the additional feature:

    const [backgroundImage, setBackgroundImage] = useState<string | undefined>(undefined);

    useEffect(() => {
        setBackgroundImage("nature-1.jpg");
    }, []);

    useEffect(() => {
        document.body.style.background = ` rgba(0, 0, 0, .3) url("/images/${backgroundImage}") no-repeat center center fixed`;
        document.body.style.backgroundSize = "cover";
        document.body.style.backgroundBlendMode = "darken";
    }, [backgroundImage]);

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

What steps can be taken to reduce the size of the cards in ant.design?

Currently, I am using the ant.design Card component to present messages in a chat webapp built with react/redux. However, each card is displaying too much space around the text. Is there a way to adjust the card so that it wraps the text more closely? htt ...

What is the best way to implement handle action for disabling an option in react-select?

Is there a way to create a custom event that will be triggered when a user clicks on a disabled option in a react-select dropdown? The issue is that events do not work when the input is disabled. Any suggestions on how to achieve this? Could wrapping the ...

Obtain data attributes using JQuery's click event handler

I'm facing an issue with a div structure setup as follows: <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class=& ...

The attribute 'map' is not found on the object of type 'List'

I am currently working on a project that involves lists, each with its own title. However, while using Map, I encountered the following error: Property 'map' does not exist on type 'List' Any suggestions on how to resolve this issue? ...

Symfony Form Validation through Ajax Request

Seeking a way to store form data with Symfony using an Ajax call to prevent browser refreshing. Additionally, I require the ability to retrieve and display field errors in response to the Ajax call without refreshing the page. I have a Symfony form setup ...

Desiring to iterate through an array of identification numbers in order to retrieve information from an external API

I have been working on an app where I retrieve IDs from one API and pass them into a second API to display the property overviewList.overview.lifeTimeData.energy for each ID. However, in my current setup, I am only able to display the property of the fir ...

Maintaining form data while dynamically including more instances of a <div> element to the form

I am currently developing a SpringMVC Webapp with a view that contains a dynamic form. The dynamic elements of the form are listed below: At the moment, I am passing the variable ${worksiteCount} from my controller to the view (stored in my portlet sessio ...

Navigating through each segment

I'm currently working on a website with sections that are set to be 100% height of the window, but at least 800px tall. My goal is to implement a smooth scrolling functionality where one scroll moves the view from section to section. However, if the ...

Vue component architecture

Just started exploring Vue last night, so the answer might be obvious. I came across components with this layout: <template> <Slider v-model="value"/> </template> <script> import Slider from '@vueform/slider' ...

What are the steps to integrate openjphjs with next.js?

I am working on a project with Next.js and need to utilize openjphjs for decoding HTJ2K pixel data. In order to incorporate openjphjs, I have included both openjphjs.js and openjphjs.wasm in a specific folder within the project structure. To address an e ...

Bottom-aligning text in Tailwind CSS

Creating two <p> tags to store text: <p v-if="my_property <= 0" class="text-green-500 text-lg font-bold">{{Math.abs(my_value)}}%</p> <p v-else class="text-red-500 text-lg font-bold">{{my_value}}%< ...

Is it possible to use React to redirect a page and display data changes?

I am not a React user but have a question about refreshing an HTML table after record operations like UPDATE, DELETE, or CREATE. Imagine a table structure like this: [New Record] John <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Tips for initializing and updating a string array using the useState hook in TypeScript:1. Begin by importing the useState hook from the

Currently, I am working on a React project that involves implementing a multi-select function for avatars. The goal is to allow users to select and deselect multiple avatars simultaneously. Here is what I have so far: export interface IStoreRecommendation ...

Transferring information between a parent and child component

I recently started learning reactjs and I encountered an issue with data communication between two components. In my application, I am using a material table to display the data. The create user form is located in a separate component. Whenever a new user ...

Utilize Custom Field to incorporate background videos from websites like Youtube or Vimeo into your content

I've been working on implementing a video background for my website. I came up with a custom code to embed URL links from Youtube and Vimeo using "oEmbed". The process is functioning well, but I'm facing some challenges in setting the background ...

Is activating the CSP policy preventing the JavaScript on the front end from transmitting cookies and the referrer header?

Upon removing the CSP policy from the backend in Node.js, everything functions correctly. However, enabling it results in a break in the JavaScript code. To investigate further, I analyzed the request headers of the AJAX requests made by my JS files. Two ...

Discover the process of extracting HTML content that's stored within a JavaScript variable

Having a HTML snippet stored in a variable, like this: var parse= 'Hello<i class="emoji emoji_smile" title=":smile:"></i><i class="emoji emoji_angry" title=":angry:"></i>World' I am looking to extract the value of the "t ...

The React production build is experiencing a problem where the Jumbotron background image fails to render

I am experiencing an issue where my image is not showing up in my React App that uses Bootstrap 4.3 after running npm run build. The image has been relocated to the Public Directory (/images/bg.jpg). While I can see it rendering correctly in the Developme ...

Encountering the following error message: "Received error: `../node_modules/electron/index.js:1:0 Module not found: Can't resolve 'fs'` while integrating next.js with electron template."

I am utilizing the electron template with next.js, and I am trying to import ipcRenderer in my pages/index.tsx file. Below is the crucial code snippet: ... import { ipcRenderer } from 'electron'; function Home() { useEffect(() => { ip ...

Why do they call me the Commander of Errors?

Alert: PowerShell has detected that a screen reader may be in use and has disabled PSReadLine for compatibility reasons. To re-enable it, simply run 'Import-Module PSReadLine'. PS C:\Web Development> scss --style expanded "c:\W ...