Skip to content

How to set background image in React?

In this quick post, we will learn how to set a background image in React. There are two ways to set background image in create-react-app – one by Inline styling and other one by external css.

Inline styling

let bgImgUrl = 'images/bg.jpg'; 

<div className = 'componentBg' 
     style = {{ backgroundImage: `url(${bgImgUrl})`,
                backgroundSize: 'cover', 
                backgroundPosition: 'center center',
                backgroundRepeat: 'no-repeat',
              }}>
</div>

External CSS

<div className = 'componentBg'
</div>
.componentBg{
  background-image: url(./images/bg.jpg);
}
See also  Resizing images in React

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.