Setting body background-image inside useEffect

Viewed 727

I want to set the background image of the document body when my app component renders. The image is in the same directory as the js file however it doesn't appear.

I have the following code.

App.js

import { useEffect } from 'react'; 
import './App.css';

function App() {

  const bg = "./clouds.png";

  useEffect(() => {
    document.body.style.backgroundImage = `url('${bg}')`;

  }, [])

  return (
    <div className="App">

    </div>
  );
}

export default App;

clouds.png is in the src directory along with App.js

2 Answers

You need to import the image.

import React, { useEffect } from "react";
import "./styles.css";
import bg from "./clouds.png";

export default function App() {
  useEffect(() => {
    document.body.style.backgroundImage = `url('${bg}')`;
  }, []);
  return <div className="App"></div>;
}

check this out: working example

Try this:

const bg = require("../assets/img/your-image.png");
document.body.style.backgroundImage = `url(${bg})`;
Related