I’m trying to create a news website with ReactJS and I’m getting three various warnings/errors when I try to run the page. I can get it to display the article link properly when I don’t include the title. I still get the two first warnings in this case, but when I try to access the article’s title it won’t load the page at all.
Any help is greatly appreciated.
The warnings/errors:
Warning: Each child in a list should have a unique "key" prop.
Warning: Invalid value for prop href
on tag.
Uncaught Error: Objects are not valid as a React child (found: object with keys {rendered}). If you meant to render a collection of children, use an array instead.
LatestArticles.js
import React, { useState, useEffect } from "react";
import Article from "./Article";
function LatestArticles() {
const [posts, setPosts] = useState(React.useState("waiting..."));
function ArticleGrabber() {
useEffect(() => {
fetch("URL")
.then((response) => response.json())
.then((data) => {
setPosts(data);
console.log(data);
})
.catch((error) =>
console.log("Authorization failed: " + error.message)
);
}, []);
}
ArticleGrabber();
return (
<div>
<h3>Latest Articles</h3>
{posts.map((post, index) => (
<ul>
<Article key={index} post={post} />
</ul>
))}
</div>
);
}
export default LatestArticles;
Article.js
import React from "react";
import "../Article.css";
function Article(post) {
return (
<div className="theArticle">
<h3>{post.post.title.rendered}</h3>
<a href={post.post.link}>Article content</a>
</div>
);
}
export default Article;
2
Answers
As far as I can see I see two Issues. 1. State inside an Inside, and the UseEffect Hook. Try this:
Warning: Each child in a list should have a unique "key" prop.
keys
you need to add it to the parent element of the item (in this case theul
tag).Warning: Invalid value for prop href on tag.
Uncaught Error: Objects are not valid as a React child (found: object with keys {rendered}). If you meant to render a collection of children, use an array instead.
For these two errors, it might be due to how you are fetching your data, but there are a few things I would look into first:
useState
andReact.useState
), instead make the default an emptyarray
.useEffect
and that should work.