Max Pan
Max Pan

Reputation: 137

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

I am trying to render multiple cards, each card for each news. But I have an error that is mentioned in the title. Something went wrong when React tries to render cards.

export default class NewsCard extends Component{

    newsService = new NewsService()

    state = {
        newsList: null,
    }

    componentDidMount() {
        this.newsService.getByCategory('Belarus').then((newsList) => {
            console.log('News: ',newsList);
            this.setState({
                newsList
            })
        })
    }

    renderItems(arr: any){
        return arr.map((article: any) => {
            console.log(article)
            return (
                <div className="card col-sm-12 col-md-6 col-lg-3">
                    <img src={article.urlToImage} alt="icon" />
                    <div className="info">
                    <p><a href={article.url}>{article.title}</a></p>
                    <p>{article.description}</p>
                    </div>
                </div>
            )
        })
    }

    render() {

        const { newsList } = this.state

        if(!newsList) {
            return <Loader />
        }

        const items = this.renderItems(newsList)

        return ({items})
    }
}

Also here I am adding a piece of code from my NewsService which may help to figure out what happens.

 async getByCategory(category: string) {
         const news = await this.newsapi.v2.topHeadlines({
            q: category,
            sortBy: 'popularity'
        })
         return await news.articles
    }

Upvotes: 0

Views: 91

Answers (1)

Jason Goemaat
Jason Goemaat

Reputation: 29204

The problem is with this:

return ({items})

Your particular error is caused because you are creating an object by using curly braces. What your code is really doing is this:

return { items: items }

That is an object and react doesn't know how to render an object.

Upvotes: 1

Related Questions