2

I have the following code below which is meant to show the "NoBillsLaptopPNG.src" 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;
`;
ghybs
  • 47,565
  • 6
  • 74
  • 99

2 Answers2

2

when you use the TestImg component, you are passing src as props to NoBillsLaptopPNG.

It would be better to name props as NoBillsLaptopPngSrc.

When you style TestImg, the NoBillsLaptopPNG input parameter is already src. Therefore, it makes no sense to refer to its src field again.

try this

 src: url(${(NoBillsLaptopPNG) => NoBillsLaptopPNG});
forlift
  • 19
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 16 '22 at 21:33
1

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";
`;
ghybs
  • 47,565
  • 6
  • 74
  • 99