Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript / Styled component passing image as props

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;

`


MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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";
`;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading