Search code examples
cssreactjsbackground-image

Changing body background image with React


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.


Solution

  • 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>
        </>
    
    }