Next.js Discord

Discord Forum

beginner: give image path via prop in custom component

Answered
Black Caiman posted this in #help-forum
Open in Discord
Black CaimanOP
So I have a button component which should create a image and a button and tried to pass a prop to src to change the image on each use.
But it throws an error saying:
Type 'string | undefined' is not assignable to type 'string | StaticImport'. Type 'undefined' is not assignable to type 'string | StaticImport'.

Here's my code:

import { ActionButtonProps } from "@/types"; import Image from "next/image"; const ActionButton = ({ buttonText, customImageStyle srcImage, }: ActionButtonProps) => { return ( <div className="lg:my-auto"> <button className="flex flex-row py-3 lg:py-0 lg:mx-8"> <Image src={srcImage} alt="download icon" width={25} height={10} className={lg:my-auto ${customImageStyle}} /> <span className="text-left ml-3 lg:my-auto">{buttonText}</span> </button> </div> ); }; export default ActionButton;

srcImageis type string in ActionButtonprops

How do I solve this?
Answered by Stoyan Paskalev
@Black Caiman Try the following:
<Image
src={srcImage as string}
...
/>
View full answer

7 Replies

@Black Caiman Try the following:
<Image
src={srcImage as string}
...
/>
Answer
@Stoyan Paskalev <@278514734632927232> Try the following: <Image src={srcImage **as string**} ... />
Black CaimanOP
oh wow. That was easy. Thank you very much.
But how does it exactly work?
you're parsing srcImage to string even tho I have alredy defined in the ActionButtonProps it should be of type string - why is this double thing needed here?
I imagine that in the ActionButtonProps, the srcImage is set with ? which makes it optional. In this line of words when something is optional it is either the type you've said it will be or undefined
And the Image component (src prop) needs a defined value, so it will not like it when you pass an optional value thus the second parsing reassuring it that this is 100% string
@Black Caiman
Black CaimanOP
Thanks for the solution and for explaining
My pleasure, have a good one!