Change background image with styled-component
Asked Answered
H

6

18

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

Hafiz answered 25/12, 2018 at 7:51 Comment(4)
Where are you assigning it dynamically?Pozzy
actually,the real code is like this{ this.props.recommendList.map((item)=>( <RecommendItem key={item.get("id")} imgUrl={item.get("imgUrl")} > ddd </RecommendItem> )) }Hafiz
Can you create stackblitz of it?Pozzy
ok,I create on the codesandbox ,url is codesandbox.io/s/wv2xvkxo8,the file is "src/pages/home/components/recommends.js",relative style file is "src/pages/home/style.js" ,line 94,thank you very muchHafiz
K
2

Move your file in public folder and try this command:

<RecommendItem imgUrl={process.env.PUBLIC_URL + '/banner.png'} >
Karolyn answered 25/12, 2018 at 9:33 Comment(3)
@Hafiz Because of your browser has access to public folder from outside.Karolyn
If you write src="abc.png" it means that your browser will make get request to http://localhost:3000/abc.png and it can't look inside src folderKarolyn
This is wrong. Look at @naved-khan answer below.Seamy
M
62

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;
`;
Mcmullen answered 1/6, 2019 at 7:1 Comment(3)
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.Fantoccini
Thank you for advice i will update it soon with exampleMcmullen
This should be the most recent answer. url(${img}) works like a charmFirm
K
2

Move your file in public folder and try this command:

<RecommendItem imgUrl={process.env.PUBLIC_URL + '/banner.png'} >
Karolyn answered 25/12, 2018 at 9:33 Comment(3)
@Hafiz Because of your browser has access to public folder from outside.Karolyn
If you write src="abc.png" it means that your browser will make get request to http://localhost:3000/abc.png and it can't look inside src folderKarolyn
This is wrong. Look at @naved-khan answer below.Seamy
A
2

import your image and try this command

import YourImage from "../filepath"

    export const RecommendItem = styled.div`
    background: url(${YourImage?.src});  
    `;
Abysm answered 21/11, 2022 at 5:24 Comment(0)
F
0
import styled from 'styled-components';
// used as 
<Heading image={require('./images/headerBackground.jpg')} />

// a styled component
const Container = styled.div`` 
// the class made as
class Heading extends Component {
  render() {
    return (
      <Container image={this.props.backgroundimage}>
          <Logo />
          <Navigation />
          <HeadingBox />
      </Container>
    )
  }
}
export default Heading;
Firm answered 21/7, 2020 at 23:12 Comment(0)
H
0

You may create next.config.js in project's root dir and add this code:

const webpack = (config, options) => {

  config.module.rules.push({
    test: /\.(png|jpe?g|gif)$/i,
    loader: 'file-loader',
    options: {
      // name: '[path][name].[ext]',

      name() {
        // `resourcePath` - `/absolute/path/to/file.js`
        // `resourceQuery` - `?foo=bar`

        if (process.env.NODE_ENV === 'development') {
          return '[path][name].[ext]';
        }

        return '[contenthash].[ext]';
      },
      publicPath: `/_next/static/images`,
      outputPath: 'static/images',
      limit: 1000,
    },
  });

  return config
}

module.exports = { webpack }

Do not forget install file-loader if not installed yet.

yarn add -D file-loader

Then in your component you may do like this:

const imgUrl = require("../../static/banner.png").default;

<RecommendItem imgUrl={imgUrl} >

Will be used abs url from bandles.

Honniball answered 20/10, 2020 at 10:46 Comment(2)
Your answer assumes that the questioner is using Next.JS. Please try to ask questions to get information about their setup if it's not clear before posting an answer that related to a specific environment like Next.JS.Oblige
Yeah, in the question, its clear that this is a reactjs and styled components Question,based on the tags below the question.Always check the tags.Sneed
G
0

You should let the function in the background-image value return a string, url(your_image_link).

<RecommendWrapper>
     <RecommendItem imgUrl="img_link" >
     </RecommendItem>  
</RecommendWrapper>

export const RecommendItem = styled.div`
    width: 280px;
    height: 50px;
    background-size: contain;
    background: ${(props) => `url(${props.imgUrl})`}; 
Goody answered 12/2, 2022 at 10:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.