Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a backgroundImage With React Inline Styles

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!

like image 986
Kris Avatar asked Aug 28 '16 20:08

Kris


People also ask

How do you add inline styles to a React?

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'}}> .

How do I style a background image in React?

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.

Are inline styles GOOD FOR React?

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.

How do you add conditional inline style in React?

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!


2 Answers

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})` 
like image 148
rgommezz Avatar answered Sep 20 '22 23:09

rgommezz


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' }} 
like image 24
Hitesh Sahu Avatar answered Sep 20 '22 23:09

Hitesh Sahu