Sometimes, we want to set a background image with React inline styles.
In this article, we’ll look at how to set a background image with React inline styles.
Set a Background Image With React Inline Styles
We can set the background image with inline styles by setting the style prop to an object with the backgroundImage property.
For instance, we can write:
import React from "react";
export default function App() {
return (
<div
style={{
backgroundImage:
"url(https://i.picsum.photos/id/219/200/300.jpg?hmac=RGnJfbO2380zLCFSj2tm_q0vW0wtw67d0fhWHX2IoDk)",
backgroundPosition: "center",
backgroundSize: "cover",
backgroundRepeat: "no-repeat",
width: "200px",
height: "200px"
}}
></div>
);
}
We set the backgroundImage to the url value of the image.
And we set the backgroundPosition to 'center' to center the background image.
backgroundSize is set to 'cover' to covert the div.
backgroundRepeat is set to 'no-repeat' to disable repetition.
width and height have the width and height of the div.
Conclusion
We can set the background image with inline styles by setting the style prop to an object with the backgroundImage property.