Home > Mobile >  Passing image object as props in TypeScript
Passing image object as props in TypeScript

Time:11-04

I want to pass an image (imported as component i.e import Event1 from "../../images/event1.jpg";). But I can not figure out what data type is it in interface. I have tried HTMLImageElement and File but it gives me an error

Type 'File | undefined' is not assignable to type 'string | undefined'.
Type 'File' is not assignable to type 'string'.

1.tsx

import React from "react";
import "./EventCard.css";

import Location from "../../images/location.png";

interface EventData {
  eventName: string;
  eventDate: string;
  eventDistance: string;
  eventImage?: File;
}

const EventCard = ({
  eventName,
  eventDate,
  eventDistance,
  eventImage,
}: EventData) => {
  return (
    <div className="event-card">
      <img src={eventImage} alt="Denim Jeans" style={{ width: "100%" }} />
      <h1 className="event-name">{eventName}</h1>
      <p className="event-date">{eventDate}</p>
      <div className="location-container">
        <img src={Location} alt="location" className="location-icon" />
        <p>{eventDistance} </p>
      </div>
    </div>
  );
};

export default EventCard;

2.tsx

import React from "react";

import Navbar from "../../components/Navbar/Navbar";
import ImageGrid from "../../components/ImageGrid/ImageGrid";
import Categories from "../../components/CategoryButton/Categories";
import EventCard from "../../components/EventCard/EventCard";
import Event1 from "../../images/event1.jpg";

const Homepage = () => {
  return (
    <div className="homepage-container">
      <Navbar />
      <div className="grid">
        <ImageGrid />
        <Categories />
        <EventCard
          eventName="Pets Event"
          eventDate="Aug to July"
          eventDistance="1.5 miles away"
          eventImage={Event1}
        />
      </div>
    </div>
  );
};

export default Homepage;

What data type do I assign image in interface?

CodePudding user response:

As a string

Note that Webpack returns url for the image(and does whole lot magic as well) on this line

import Event1 from "../../images/event1.jpg"

So Event1 here is not of type File, but of type string

  • Related