I want to add a background image in React.js by using a style definition, which works:
let imgUrl = 'images/berlin.jpg'
let styles = {
root: {
backgroundImage: 'url(' + imgUrl + ')',
overflow: 'hidden',
},
...
As you can see, the image repeats in x-direction. So I wanted to extend it by:
let imgUrl = 'images/berlin.jpg'
let styles = {
root: {
backgroundImage: 'url(' + imgUrl + ')',
backgroundImage: {
flex: 1,
resizeMode: 'cover', // or 'stretch'
},
overflow: 'hidden',
},
...
But the image is not loaded anymore:
So how to set the background image and adjust it in React.js?
Method 1: Using inline CSS: In this method, we add the style attribute inside the element itself. In App. js, We will add a style attribute inside the div element and set the background image for a div element using inline CSS.
Conditional Changing the Background Color in Reactimport React from 'react'; import './App. css'; function App() { const isBackgroundRed = true; return ( <div className={isBackgroundRed ? 'background-red' : 'background-blue'} /> ); } export default App; JSX allows us to write JavaScript inside of HTML.
To set a background image with inline styles in React: Set the style prop on the img element. Set the backgroundColor property in the style object. For example, backgroundImage: url(${MyBackgroundImage}) .
To change background color on click in React:Set the onClick prop on the element. When the element is clicked, set the active state. Use a ternary operator to conditionally set the background color based on the state variable.
This works:
let imgUrl = 'images/berlin.jpg'
let styles = {
root: {
backgroundImage: 'url(' + imgUrl + ')',
backgroundSize: 'cover',
overflow: 'hidden',
},
...
Clarifing another answer
let imgUrl = 'images/berlin.jpg'
let styles = {
root: {
backgroundImage: `url(${ imgUrl })`
backgroundRepeat : 'no-repeat',
backgroundPosition: 'center',
}
}
If you use an image as background, is better to use the 'backgroundImage' property.
If you use the 'background' property, this may cause issues on reloading the component (e.g. 'cover' attribute will not apply properly).
Solution proposed:
let imgUrl = 'images/berlin.jpg';
<div className = 'Component-Bg'
style = {{ backgroundImage: `url(${imgUrl})`,
backgroundSize: 'cover',
backgroundPosition: 'center center',
backgroundRepeat: 'no-repeat',
}}>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With