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});
`;
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
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; `;
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.
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;
`;
Move your file in public folder and try this command:
<RecommendItem imgUrl={process.env.PUBLIC_URL + '/banner.png'} >
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