简体   繁体   中英

How to pass an image as prop in react/typescript to another component

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]

```

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: inte.net 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.",
  },
];

Suggestion 1 : img: { inte.net } means img: { inte.net: inte.net } . your type is expecting img: inte.net

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM