5

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>
  );
1
  • Does your Card component accepts a card prop ? Commented Oct 24, 2019 at 21:15

2 Answers 2

5

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>
);
Sign up to request clarification or add additional context in comments.

Comments

0

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})
}

1 Comment

@Kim Lee did any answer help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.