Search code examples
reactjsstyled-components

How to inject background image url into styled-components


I am using styled-components as a design library, I created a div that will hold a background image with its properties, if I inject the image url from outside the styled components it doesnt take and and does some mistakes.

Ill copy some code:

image-div component as styled component:

const ImageDiv = styled.div`
  height: 100%;
  width: 100%;
  float: left;
  background-repeat: no-repeat;
  background-position: left;
  background-size: cover;

`
export default ImageDiv;

using the ImageDiv on a screen and passing it a background image doesnt take the background properties from above

<ImageDiv style={{ backgroundImage: `url(${signin})` }} src = {signin} alt="logo" />

I will like to be able to pass the url as a prop and inject it into the styled component from above


Solution

  • You could simply pass it as another prop, then use it inside styled component as background-image property.

    <ImageDiv bg={signin} src={signin} alt="logo" />
    
    const ImageDiv = styled.div`
       background-image: url(${(props) => props.bg});   
    `;