Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a background image in reactjs?

I have a reactjs/webpack app and trying to set a background image for the bodytag:

body{     background: url("../images/some-background.jpg");     background-size:contain;     background-position:top;     background: cover; } 

However after loading the components the body style is not present in the page.It shows up in the console though. Is there a way to display a background image in the main page whilst having the CSS rule in the CSS file that is loaded by webpack?Is this because reactjs does something I am not aware off?

like image 985
bier hier Avatar asked Jun 28 '17 07:06

bier hier


People also ask

How do I add a background image in React JS?

export default App; Output: Method 5: Add background image from src/ folder If the image resides inside the src directory, the user can import it inside the component filer and set it as the background image. In this file, we will import the image and set it as a background image of the div element.

How do I change the background in React?

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.

How do you change the background of a dynamic image in React?

You haven't specified when would you like to change backgroundImage , so I've created version which changes it with onClick : React. createClass({ getInitialState: function () { nextImg: false, }, handleClick: function () { this. setState({ nextImg: !


2 Answers

You need to store your images in the Public folder of your project. You can refer to the public folder using a forward slash / and access your images from there.

For example:

<img src="/background.jpg" /> 

You can do the same in a CSS File:

.background {    background-image: url("/background.jpg"); } 
like image 79
Richard Bonneau Avatar answered Sep 28 '22 00:09

Richard Bonneau


Background should be already a String:

backgroundImage: "url(" + Background + ")"

You can also use ES6 string templates:

backgroundImage: `url(${Background})` 

you should read this it might help -

https://www.davidmeents.com/blog/how-to-set-up-webpack-image-loader/

like image 28
Stacy Chen Avatar answered Sep 28 '22 00:09

Stacy Chen