Last updated: Apr 7, 2024
Reading time·2 min
To set a background image with inline styles in React:
style
prop on the img
element.backgroundColor
property in the style
object.url(${MyBackgroundImage})
.// 👇️ 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 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.
I've also written an article on how to use a ref to change an element's style.
Here is an example that sets a remote background image using inline styles.
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.
The dollar sign and curly braces syntax allows us to use placeholders that get evaluated.
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.
If you need to center a div or a component horizontally and vertically, check out the following article.