Search code examples
next.jsstyled-components

Passing image as props to styled components in Next.js


I'm trying to pass an image to set as my background in Next whit Styled Components but causes an unexpected behavior.

Hero Component:

import djEventImg from '@/public/images/dj-event.jpg'
import { Hero } from './ShowCase.styles'

const ShowCase = () => {
  return <Hero image={djEventImg}></Hero>
}

export default ShowCase

Styled Component:

import styled from 'styled-components'

export const Hero = styled.div`
  // background image props
  background-image: url(${(props) => props.image});
  width: 100;
  height: 300px;
`


Solution

  • I replicated your code in my local mashine and got an image with this code

    Hero Component:

    import djEventImg from '/public/images/dj-event.jpg'
    import { Hero } from './ShowCase.styles'
    
    const ShowCase = () => {
      return <Hero image={djEventImg}></Hero>
    }
    
    export default ShowCase
    

    Styled Component:

    import styled from 'styled-components'
    
    export const Hero = styled.div`
      background-image: url(${props => props.image.src});
      width: 100%;
      height: 300px;
      background-repeat: no-repeat;
    `;