Setting A Full Background Image in React

Setting A Full Background Image in React

Mahesh Rao's photo
Mahesh Rao
·Jun 18, 2021·

So, I have been struggling for a while in how to set a full sized background image in react framework. This can be quite tricky since React works a bit different compared to normal website design. When I figured out how to do it, I had a true urge to share with you guys. So, let's check out how to set a background image in react.

  • First, let's check out the code in App.css. The only thing that you must be careful here is to set height property to 100vh instead of 100%. To set the image URL as exactly as I did in the code below, image directory should be positioned as:
|__ assets
        |__images
             |__bg.jpg
|__App.css
  • This is important because if image URL isn't set right , then you will be facing error such as can't resolve image file URL.
/* Desktop Version */
.desktop-bg {
   /* The image used */
   background-image: url("./assets/images/bg.jpg");

   /* Full height */
   height: 100vh;

   /* Center and scale the image nicely */
   background-position: center;
   background-repeat: no-repeat;
   background-size: cover;
}
  • Now you can go ahead add the code in any file where you have html components. I believe you have a clear idea on how to render HTML components in React so I aren't going too much in detail in it.
<div className="desktop-bg"></div>
  • So, that's it , now you can have a full-sized background image in your site as the one you see below.

image.png

 
Share this