Search code examples
reactjsstyled-components

Add srcSet to styled-component themed image


I have multiple themes for my website. I'm attempting to add a srcSet to an image like this:

export const Header = styled.img.attrs({
  src: props => props.theme.images.Header1x,
  srcSet: `${props => props.theme.images.Header1x} 1x, ${props => props.theme.images.Header2x} 2x, ${props => props.theme.images.Header3x} 3x`,
})`
  height: 42px
`;

The src attribute is proper, but srcSet is not:

<img src="/images/header.jpg" srcset="function (props) {
    return props.theme.images.Header1x;
  } 1x, function (props) {
    return props.theme.images.Header2x;
  } 2x, function (props) {
    return props.theme.images.Header3x;
  } 3x" class="sc-VJcYb epAqoN">

styled-components theming feature is wonderful, and I'd like to keep all my theming organized with it, but I can't think of a way to properly build a srcSet with it. Anyone have any strategies, or do I need to go in another direction entirely?


Solution

  • The value of your srcSet property is a template string but should be a function that returns a string.

    export const Header = styled.img.attrs({
      src: props => props.theme.images.Header1x,
      srcSet: props => `${props.theme.images.Header1x} 1x, ${props.theme.images.Header2x} 2x, ${props.theme.images.Header3x} 3x`,
    })`
      height: 42px
    `;