How to use React + TypeScript to render components by looping through an array?

Viewed 8123

I have tried to loop over items of an array but I am missing some typing for my components in TypeScript. I have tried Card<any or Card<IProps> with the interface being defined below (not being used below).

This is the error I've gotten so far I get this error.

Type '{ key: number; card: { name: string; image: string; id: number; }; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'. Property 'card' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.

I am curious to learn what it is exactly that I am missing here?

const cards = [
  {
    name: "a",
    image: "red",
    id: 1
  },
  {
    name: "b",
    image: "blue",
    id: 2
  },
  {
    name: "c",
    image: "green",
    id: 3
  }
];

interface IProps {
  card: {
    name: string;
    image: string;
    id: number;
  };
  key: string;
}


...(Stateless component logic here)...

const renderCards = () => {
    return cards.map(card => {
      return <Card key={card.id} card={card} />;
    });
  };

  return (
    <div>

      <CardContainer>{renderCards()}</CardContainer>
    </div>
  );
2 Answers

I would need to see your Card component implementation, but I am guessing the following should helpĀ :

interface ICard {
  name: string;
  image: string;
  id: number;
}

interface IProps {
  card: ICard;
  key: string;
}

const cards: ICard[] = [
  {
    name: "a",
    image: "red",
    id: 1,
  },
  {
    name: "b",
    image: "blue",
    id: 2,
  },
  {
    name: "c",
    image: "green",
    id: 3,
  },
];

const Card: React.FC<{ card: ICard }> = ({ card }) => {
  return <div>{card.name}</div>;
};

const renderCards = () => {
  return cards.map(card => {
    return <Card key={card.id} card={card} />;
  });
};

return (
  <div>
    <CardContainer>{renderCards()}</CardContainer>
  </div>
);

Ensure you're including a children param in the interface of your Props

e.g.

interface CardProps {
card:{
    name: string;
    image: string;
    id: number;
  },
  children: React.ReactNode
}


const Card= ({
  card,
  children,
}: CardProps) => {
// and do whatever you like with `card` prop here
return ( {children})
}

Related