Home > database >  TypeScript / Styled component passing image as props
TypeScript / Styled component passing image as props

Time:10-13

I have the following code below which is meant to show the "NoBillsLaptopPNG.src" is on the screen but no image is being rendered.

The images are being imported fine, but not sure why the image is not being displayed.


 import NoBillsMobilePNG from "../../public/assets/quotes/no-bills-mobile.png"
 import NoBillsLaptopPNG from "../../public/assets/quotes/no-bills-laptop.png"


 export const NoBillsSummary = () => {
  return <div>
      <TestImg NoBillsMobilePNG ={NoBillsMobilePNG.src}  NoBillsLaptopPNG ={NoBillsLaptopPNG.src} ></TestImg >         

  </div>;
};

const TestImg = styled.img<{ NoBillsMobilePNG: string ; NoBillsLaptopPNG: string }>`
   // the reason the img is being passed in as props as media query will later be added to switch between images

        src: url(${(NoBillsLaptopPNG) => NoBillsLaptopPNG.src});

        width : 126.07px;
        height : 107.59px;
        margin-top: 2px;

`


CodePudding user response:

try this

 src: url(${(NoBillsLaptopPNG) => NoBillsLaptopPNG});

CodePudding user response:

With styled-components, when you interpolate a function within your style, styled-components will call that function with the entire props of the component.

Therefore, you have to either refer to a specific member, or destructure it, like for a usual React Function Component.

Next, it is normally not possible to change the src attribute of an <img> through style only (CSS). However, it is still possible to change its content.

Finally, as implied by @forlift's answer, you already pass just the .src value to the prop, so there is no need to re-access it again.

const TestImg = styled.img<{
  NoBillsMobilePNG: string;
  NoBillsLaptopPNG: string;
}>`
  // Notice the destructuring of the props
  content: url(${({ NoBillsLaptopPNG }) => NoBillsLaptopPNG});

  width : "226.07px";
  height : "207.59px";
  margin-top: "2px";
`;
  • Related