Home > Software design >  Error: Objects are not valid as a React child (found: object with keys
Error: Objects are not valid as a React child (found: object with keys

Time:02-19

Hi guys if you can help me understand what I'm doing wrong?

This error notes:

Error: Objects are not valid as a React child (found: object with keys {id, title, bodyText, icon}). If you meant to render a collection of children, use an array instead.

My code snippet:

  if (cards) {
    const filteredCards = cards.filter((card: { title: string }) => {
      return card.title.toLowerCase();
    });
    return filteredCards;
  }

console.log(cards) gives:

cards (4) [{…}, {…}, {…}, {…}]

if I'm using an array there as the error notes, isn't this redundant?

I'm kind of confused.

CodePudding user response:

You should return an array of JSX or an array of strings. I guess you meant to get the lowerCase of titles. For that, you should be using map instead of filter. Currently filteredCards is an array of JSON in the format same as an item cards.

Try like this.

  if (cards) {
    const filteredCards = cards.map((card: { title: string }) => {
      return card.title.toLowerCase();
    });
    return filteredCards;
  }
  • Related