Setting a background image with inline Styles in React

avatar

Borislav Hadzhiev

Last updated: May 1, 2022

banner

Photo from Unsplash

Setting a background image with inline Styles in React #

To set a background image with inline styles in React:

  1. Set the style prop on the img element.
  2. Set the backgroundColor property in the style object.
  3. For example, backgroundImage: url(${MyBackgroundImage}).
App.js
// 👇️ import the image import MyBackgroundImage from './background-image.webp'; export default function App() { const externalImage = 'https://bobbyhadz.com/images/blog/react-prevent-multiple-button-clicks/thumbnail.webp'; return ( <div style={{ backgroundImage: `url(${MyBackgroundImage})`, // backgroundImage: `url(${externalImage})`, backgroundSize: 'cover', backgroundRepeat: 'no-repeat', backgroundPosition: 'center', height: '500px', }} > <h2 style={{color: 'white'}}>Hello world</h2> </div> ); }

The example shows how to set a local or an external image as a background image using inline React styles.

The example assumes that you have an image named background-image.webp in the same folder as the App component.

For local images, make sure to specify the correct path to the image file (including the extension).

For example, if you are importing an image from one directory up, you would import as import MyImage from '../background-image.webp'.

The image has to be located in the src directory of your project.

You can either pass an imported image to the url() CSS function or a remote URL that points to your external image.

Here is an example that uses a remote background image.

App.js
export default function App() { const externalImage = 'https://bobbyhadz.com/images/blog/react-prevent-multiple-button-clicks/thumbnail.webp'; return ( <div style={{ backgroundImage: `url(${externalImage})`, backgroundSize: 'cover', backgroundRepeat: 'no-repeat', backgroundPosition: 'center', height: '500px', }} > <h2 style={{color: 'white'}}>Hello world</h2> </div> ); }

Notice that we use a template literal to interpolate a variable in a string.

Note that the string is enclosed in backticks ``, not in single quotes.

The dollar sign and curly braces syntax allows us to use placeholders that get evaluated.

App.js
const externalImage = 'https://example.com/img.png'; const result = `url(${externalImage})`; // 👇️ url(https://example.com/img.png) console.log(result);

By default, the template literal concatenates the parts into a string.

This is exactly what we need because the url() CSS function is used to include a file and takes an absolute URL, a relative URL, or a data URL as a parameter.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.