manmeet mishra
manmeet mishra

Reputation: 19

Getting error Objects are not valid as a React child

I am learning react.js. And I am running the App.js but I am getting error as : - × Error: Objects are not valid as a React child (found: object with keys {blogCards}). If you meant to render a collection of children, use an array instead

Can anyone tell me why this error because I am new in react.js

import logo from './logo.svg';
import './App.css';
import React from 'react';

function App() {
  const blogArr = [
    {
    id : 1,
    title: 'Blog Title 1',
    description : 'Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor'
  },
  {
    id : 2,
    title: 'Blog Title 2',
    description : 'Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor'
  },
  {
    id : 3,
    title: 'Blog Title 3',
    description : 'Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor Lorem Ipsum Dolor'
  }]
  
  const blogCards = blogArr.map((item,pos) => {
    console.log(item)
    
    return (
      <div className="BlogCard" key={pos}>
        <h3>{item.title}</h3>
        <p>{item.description}</p>
      </div>
        
    );
  })

   return (
    <div className="App">
      {
        {blogCards}
      }
    </div>
  );

}



export default App;

Upvotes: 0

Views: 53

Answers (2)

Alwani Anis
Alwani Anis

Reputation: 258

   <div className="App">
      {
        blogCards
      }
    </div>

Upvotes: 1

edemaine
edemaine

Reputation: 3130

As @zsolt-meszaros mentions in comments, the problem is with this code:

    <div className="App">
      {
        {blogCards}
      }
    </div>

The outer braces on their own lines leave JSX mode and enter JavaScript mode. In JavaScript, {blogCards} is equivalent to {"blogCards": blogCards}, i.e., make an object with one property with key "blogCards" and value equal to the blogCards variable. Hence React gets an object and complains.

You just need to change your code to:

    <div className="App">
      {blogCards}
    </div>

Upvotes: 1

Related Questions