I'm trying to access a static image to use within an inline backgroundImage
property within React. Unfortunately, I've run up dry on how to do this.
Generally, I thought you just did as follows:
import Background from '../images/background_image.png'; var sectionStyle = { width: "100%", height: "400px", backgroundImage: "url(" + { Background } + ")" }; class Section extends Component { render() { return ( <section style={ sectionStyle }> </section> ); } }
This works for <img>
tags. Can someone explain the difference between the two?
Example:
<img src={ Background } />
works just fine.
Thank you!
To set inline styles in React: Set the style prop on the element to an object. Set the specific CSS properties and values to style the element. For example, <div style={{backgroundColor: 'salmon', color: 'white'}}> .
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.
But if this concept works fine, why should we stop using it? The inline styling concept might not help you to build the best React components in your app. If you're planning to build a very performant, scalable, and rich application inline styling is not the right option for you.
Conditional Styling with Inline Styles Add the following code to your App. js: import { React, useState } from "react"; import "./App. css" function App() { const styles = { popup:{ display:"none", opacity:"0" } }; return ( <div className="main"> <button className="open_button">Open!
The curly braces inside backgroundImage property are wrong.
Probably you are using webpack along with image files loader, so Background should be already a String: backgroundImage: "url(" + Background + ")"
You can also use ES6 string templates as below to achieve the same effect:
backgroundImage: `url(${Background})`
Inline style to set any image full screen:
style={{ backgroundImage: "url(" + "https://images.pexels.com/photos/34153/pexels-photo.jpg?auto=compress&cs=tinysrgb&h=350" + ")", backgroundPosition: 'center', backgroundSize: 'cover', backgroundRepeat: 'no-repeat' }}
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