skip to Main Content
  import React from 'react'

  const desserts = [
    {
      title: 'Chocolate Cake',
      description: 'Chocolate cake is a cake flavored with melted chocolate',
      calories: 500,
    },
    {
        title: 'Chocolate Cake',
        description: 'Chocolate cake is a cake flavored with melted chocolate',
        calories: 500,
      }
  ];
  const CourseraList = () => {
    
    const newDesserts= desserts.map((dessert) => {
        return {
            ...dessert,
            title: dessert.title.toUpperCase(),
            kCal: dessert.calories / 1000,
        }
    })
    return (
      <div>
        {newDesserts}
      </div>
    )
  }
  
  export default CourseraList

Why is it showing error?
I am returning an object.

Error:

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

2

Answers


  1. Error says, use like this. Sorry for fast answer, I don’t have so much time to detail rn.

      import React from 'react'
    
      const desserts = [
        {
          title: 'Chocolate Cake',
          description: 'Chocolate cake is a cake flavored with melted chocolate',
          calories: 500,
        },
        {
            title: 'Chocolate Cake',
            description: 'Chocolate cake is a cake flavored with melted chocolate',
            calories: 500,
          }
      ];
      const CourseraList = () => {
        
        const newDesserts= desserts.map((dessert) => {
            return <>
                       <p>dessert.title</p>
                   </>
        })
        return (
          <div>
            {newDesserts}
          </div>
        )
      }
      
      export default CourseraList
    
    Login or Signup to reply.
  2. You’re trying to render an array of objects directly within JSX, which is not allowed in React. React expects JSX to represent components or primitive values, not plain objects.

    import React from 'react';
    
    const desserts = [
      {
        title: 'Chocolate Cake',
        description: 'Chocolate cake is a cake flavored with melted chocolate',
        calories: 500,
      },
      {
        title: 'Chocolate Cake',
        description: 'Chocolate cake is a cake flavored with melted chocolate',
        calories: 500,
      },
    ];
    
    const CourseraList = () => {
      const newDesserts = desserts.map((dessert, index) => (
        <div key={index}>
          <p>Title: {dessert.title}</p>
          <p>Description: {dessert.description}</p>
          <p>Calories: {dessert.calories}</p>
        </div>
      ));
    
      return <div>{newDesserts}</div>;
    };
    
    export default CourseraList;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search