Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change background image with styled-component

I want to change the backgroundImage dynamiclly, when i try it follow as, it did not work,but when i open the devtools in chrome, can show that background

<RecommendWrapper>
     <RecommendItem imgUrl="../../static/banner.png" >
     </RecommendItem>  
</RecommendWrapper>

export const RecommendItem = styled.div`
    width: 280px;
    height: 50px;
    background-size: contain;
    background: url(${(props)=>props.imgUrl});  
`;

enter image description here

if i use like this,it can work,but can't change image dynamic.

import banner from "../../statics/banner.png"
export const RecommendItem = styled.div`
    width: 280px;
    height: 50px;
    background-size: contain;
    background:url(${banner}); 
`;

and if i use a network image(url likes "https://syean.cn/img/avatar.jpg") ,it also can work

like image 318
syean Avatar asked Dec 25 '18 07:12

syean


People also ask

How do you pass a background image in styled-components?

In this post, we'll look at how to solve the How To Add Background Image In Styled Components programming puzzle. import styled from 'styled-components'; import img from './img/bg. gif'; const Content = styled. div` border: 1px solid #000; background-image: url(${img}); width: 2000px; height: 2000px; `;

How do you change the background of a dynamic 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.


2 Answers

React, Gatsby and Next.js all generally use Webpack, which compiles your site before deployment. They will minify imagery and change each image's path.

In order to get images to load properly, you have to reference them dynamically as an import. This way, the variable URL will still work after Webpack does its thing.

import styled from 'styled-components';
import img from './img/bg.gif';
    
const Content = styled.div`
  border: 1px solid #000;
  background-image: url(${img});
  width: 2000px;
  height: 2000px;
`;
like image 104
Naved Khan Avatar answered Nov 18 '22 00:11

Naved Khan


Move your file in public folder and try this command:

<RecommendItem imgUrl={process.env.PUBLIC_URL + '/banner.png'} >
like image 44
Leri Gogsadze Avatar answered Nov 17 '22 23:11

Leri Gogsadze