I'm new to typescript and don't know how to pass an image (svg) in a different component as a prop in typescript
this is my code:
Image Import
import internet from "./assets/internet.svg"
passing it products array along with the image into Products component
function App() {
const products = [
{
id: 1,
img: { internet },
heading: "Access a private marketplace",
desc:
"Product Description.",
},
];
return (
<main>
<Products products={products} />
</main>
);
}
Products.tsx:
```
type Product = {
id: number;
img: any; // unsure about type, "string" didn't work so i chose "any"
heading: string;
desc: string;
};
type ProductsProps = {
products: Product[];
};
const Products = ({ products }: ProductsProps) => {
return (
<div>
{products.map((product, id) => (
<div>
id: {product.id}
img: <img src={product.img} alt={product.img} />
heading: {product.heading}
desc: {product.desc}
</div>
))}
</div>
);
};
export default Products;
when i run this the alt tag returns [object Object]
```
CodePudding user response:
I'm guessing you also weren't able to display your image properly. The problem lies in the way you declared your products array in App.tsx.
On line 6, img
's type is an object with the sole key: internet
such as:
const projectImg = {
internet: "link.to.your.image.svg"
}
This prevents your Products
component from rendering the image properly, since the <img/>
tag expects product.img
to be a string.
Replace your products definition with the following code and it should run just fine.
import internet from "./assets/internet.svg";
const products = [
{
id: 1,
img: internet, // notice the lack of curly braces
heading: "Access a private marketplace",
desc: "Product Description.",
},
];
CodePudding user response:
Suggestion 1: img: { internet }
means img: { internet: internet }
.
your type is expecting img: internet
Suggestion 2: Assuming you are expecting only SVGs are your images, SVGs are also elements so you can use them directly without an IMG tag like below.
<div>
id: {product.id}
img: {product.img}
heading: {product.heading}
desc: {product.desc}
</div>
In case you want to type the SVG image property you can reference https://stackoverflow.com/a/63165963/14362614