Passing Props to React Styled Components in Typescript

Viewed 2873

I wrote this styled component in typescript. this is as per their documentation

    import matrix from '../img/matrix.jpg';
    const Style = styled.div`
      .fixed {
        background-image: url(${props => props.image ? props.image : "../img/default.jpg"})
        z-index: -999!important;
        display: block;
        top: 0;
        left: 0;
      }
    `;
    export const FixedBackground = () => {return (
      <Style image={matrix}>
      </Style>
    )};

but it throws a compile error

Property 'image' does not exist on type 'ThemedStyledProps<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, \"slot\" | \"style\" | \"title\" | ... 251 more ... | \"onTransitionEndCapture\"> & { ...; }, any>'

I also tried to write my styled component like

    const Style = (props: {image: string}) => {return (styled.div`
      .fixed {
        background-image: url(${props.image})
        z-index: -999!important;
        display: block;
        top: 0;
        left: 0;
      }
    `)};
    export const FixedBackground = () => {return (
      <Style image={matrix}>
      </Style>
    )};

but again it throws compile time error

Type '{ children: never[]; image: string; }' is not assignable to type 'IntrinsicAttributes & { image: string; }'. Property 'children' does not exist on type 'IntrinsicAttributes & { image: string; }'."

2 Answers

Try like this:

interface StyleProps {
  image?: string;
} 

const Style = styled.div<StyleProps>`
      .fixed {
        background-image: url(${props => props.image ? props.image : "../img/default.jpg"})
        z-index: -999!important;
        display: block;
        top: 0;
        left: 0;
      }
    `;

Looking at the link you sent. I think it is not being passed because you are using a simple element, and since the image attribute isn't a known attribute for the div element, it doesn't get passed.

The section just above "Passed props", "Styling any component" may give you what you need.

Passed props If the styled target is a simple element (e.g. styled.div), styled-components passes through any known HTML attribute to the DOM. If it is a custom React component (e.g. styled(MyComponent)), styled-components passes through all props.

Related