skip to Main Content

So, I’m trying to create a React App that changes the background image of the body. I did this by giving the body in my index.html an id of "body." I can get this to work with changing the background COLOR just fine. When I try to reassign the background IMAGE, though, I can’t seem to get it to work no matter what I try.

This works:

document.getElementById("body").style.backgroundColor = "blue";

This doesn’t:

    import explosion from "./explosion.png";

function Boom(){
document.getElementById("body").style.backgroundImage = "url('" + {explosion} +
"')";

Why? I’ve tried writing this many different ways.

3

Answers


  1. this worked for me :

    import { useEffect } from "react";
    import img from './img.png';
    
    export default function App(){
    
        useEffect(()=>{
            document.getElementById('body').style.backgroundImage = `url('${img}')`;
        })
        return <>
        <div id="body"
        style={{height:'300px'}}
        >
    
        </div>
        </>
    
    }
    

    or you can use inline css style :

    import img from './img.png';
    
    export default function App(){
        return <>
        <div id="body"
        style={{
            height:'300px',
            backgroundImage: `url('${img}')`,
        }}
        >
    
        </div>
        </>
    
    }
    
    Login or Signup to reply.
  2. you need to pass the URL of the image as a string, without wrapping it in curly braces {}

    Login or Signup to reply.
  3. You can try this code

    import { useEffect } from "react";
    
    export default function App() {
      const bgUrl =
        "https://images.unsplash.com/photo-1605106250963-ffda6d2a4b32?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=880&q=80";
    
      /*useEffect Hook allows you to perform side effects in your components. Such as fetching data, directly updating the DOM, and timers*/
      useEffect(() => {
        Boom();
      }, []);
    
      const Boom = () => {
        document.getElementById("body").style.backgroundImage = `url(${bgUrl})`;
      };
    
      return (
        <div className="App">
          <h1>Hello World!</h1>
        </div>
      );
    }
    

    here’s a link to the working demo Change Background Image

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search