Error: Objects are not valid as a React child in Reactjs

Dung Do Tien May 23 2022 47

 Hello Guys, I have created a small React application that helps me get data from an API and display it to the end-user.  You can see it below:

 import * as React from 'react';
import React, { Component } from 'react';
import axios from 'axios';

export default class News extends Component {
  constructor(props) {
    super(props);

    this.state = {
      news: [],
    };
  }

  componentDidMount() {
    axios
      .get('https://hn.algolia.com/api/v1/search?query=react')
      .then((result) =>
        this.setState({
          news: result.data.hits,
        })
      );
  }

  render() {
    return (
      <div>
        {this.state.news}
      </div>
    );
  }
}

But when I ran the code below I get an error Objects are not valid as a React child. If you meant to render a collection of children, use an array instead. I debugged but this.state.news is has data, it's not null.

 Error: Objects are not valid as a React child (found: object with keys {created_at, title, url, author, points, story_text, comment_text, num_comments, story_id, story_title, story_url, parent_id, created_at_i, relevancy_score, _tags, objectID, _highlightResult}). If you meant to render a collection of children, use an array instead.
    at throwOnInvalidObjectType (react-dom.development.js:14757:9)
    at createChild (react-dom.development.js:15009:7)
    at reconcileChildrenArray (react-dom.development.js:15274:25)
    at reconcileChildFibers (react-dom.development.js:15691:16)
    at reconcileChildren (react-dom.development.js:19971:28)
    at updateHostComponent$1 (react-dom.development.js:20733:3)
    at beginWork (react-dom.development.js:22447:14)
    at beginWork$1 (react-dom.development.js:27381:14)
    at performUnitOfWork (react-dom.development.js:26516:12)
    at workLoopSync (react-dom.development.js:26422:5)

How can I fix this issue?

Thank you in advance!

Have 1 answer(s) found.
  • m

    mohammed moulakhnif May 23 2022

    Your data this.state.news is an array, so you would have to iterate over the array using Array.prototype.map() for it to work. 

    For example:

     render() {
        return (
          <div>
            {this.state.news.map((topic) => (
              <li key={topic.objectID}>{topic.title}</li>
            ))}
          </div>
        );
      }

    I hope this answer will useful to you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close