Home > Software engineering >  Connecting body background image to a state in next.js
Connecting body background image to a state in next.js

Time:01-29

I am trying to make a pomodoro timer using Next.js And I need to connect body's background image to a state. But my code doesn't work.

I used this code to update 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;

But the styling doesn't apply and I can't see any failed requests to image. (I'm sure that image exists) What can i do to fix it? Or are there any other solutions that makes the image fit in the background even if size changes?

CodePudding user response:

Remove the semicolon from the background string, it is not CSS.

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

CodePudding user response:

What a mistake! Anyways, thanks for the help. I fixed it and added the functionality:

    const [bgImageName, setBgImageName] = useState<string | undefined>(
        undefined
    );

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

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