DEV Community

Haruka Kato
Haruka Kato

Posted on

How to set background image in React

Having trouble setting a background image in your react project? I was looking at many posts on websites and I was finally able to solve this problem.

import candles from './Picture/candles.jpg';

<Box
    class="candles"
    style={{
    backgroundImage: `url(${candles})`,
}}>

Enter fullscreen mode Exit fullscreen mode

I was trying this way for a while and it looked nothing wrong with it.

import candles from './Picture/candles.jpg';

<Box
    class="candles"
    style={{
    backgroundImage: `url(${candles})`,
    backgroundSize: "cover",
    height: "100vh",
    color: "#f5f5f5"
}}>
Enter fullscreen mode Exit fullscreen mode

This worked and I found out that the image I was using was bigger than div default so it needed to be specified its height. So if you are struggling to set your background image in react, you can try this!

Hope this is helpful for you :)

Top comments (4)

Collapse
 
naveen1994rai profile image
Naveen Rai

Works wonders !!

Collapse
 
spirit820 profile image
spirit820

very helpful! Thank you!

Collapse
 
jjrh92 profile image
Julio

Thank you.

Collapse
 
heine5150 profile image
heine5150

That was super helpful! Thank you :)