I am using an API with a Reactjs project this is a preview of an object from my API:
{
"id": "786e8fe8-ab7a-4659-8d89-7ca3d7aafa78",
"owner": {
"id": "19b70b73-94a4-4bb7-baf1-73103d793c91",
"name": "John",
"email": "[email protected]",
"username": "John",
"location": null,
"short_intro": null,
"bio": "",
"profile_image": "/images/profiles/user-default.png",
"social_github": null,
"social_twitter": null,
"social_linkedin": null,
"social_youtube": null,
"social_website": null,
"created": "2021-08-12T21:04:41.277498Z",
"user": 2
},
"tags": [
{
"id": "e76121ab-2397-4b75-993d-63d236d32530",
"name": "Django",
"created": "2021-08-12T23:31:15.681455Z"
}
],
"reviews": [
{
"id": "94e8682e-e73d-4df4-92ab-f9a71195ef90",
"body": null,
"value": "up",
"created": "2021-08-22T07:54:39.070325Z",
"owner": "19b70b73-94a4-4bb7-baf1-73103d793c91",
"project": "786e8fe8-ab7a-4659-8d89-7ca3d7aafa78"
}
],
"title": "zain's 4 project",
"description": "John project",
"featured_image": "/images/unicrorn_fee_gwilI9S.PNG",
"demo_link": null,
"source_link": null,
"vote_total": 1,
"vote_ratio": 100,
"created": "2021-08-20T05:39:17.087447Z"
}
While I'm able to get the id and the owner.name in my frontend I'm not able to get the tags object which is inside an array.
If I try to get the tags by using a map function in React I get an error:
Error: Objects are not valid as a React child (found: object with keys {id, name, created}). If you meant to render a collection of children, use an array instead.
Here is my React code:
import React, { useState, useEffect } from "react";
function Projects() {
const [projects, setProjects] = useState([]);
useEffect(() => {
fetch("http://127.0.0.1:8000/api/projects/")
.then((res) => {
return res.json();
})
.then((res) => {
setProjects(res);
})
.catch((err) => console.log(err));
}, []);
return (
<section class="projectsList">
{projects.map((project) => (
<div class="container">
<div class="grid grid--three">
<div class="column">
<div class="card project">
<a
href=""
class="project"
>
<img
class="project__thumbnail"
src=""
alt="project thumbnail"
/>
<div class="card__body">
{project.title}
<h3 class="project__title"></h3>
<p>
<a
class="project__author"
href=""
>
By
{project.owner.name}
</a>
</p>
<p class="project--rating">
<span>{project.vote_ratio}%</span>
<br />
Positive Feedback ( Positive
Feedback ({project.vote_total}) Vote
{project.vote_total}
</p>
<div class="project__tags">
{/*---Here is the problem---*/}
{project.tags.map(tag => (
<span class="tag tag--pill tag--main">
<small>{tag}</small>
</span>
))}
</div>
</div>
</a>
</div>
</div>
</div>
</div>
))}
</section>
);
}
export default Projects;
How can I get the tags object which is inside an array?
tagin the map callback. React is complaining that you are trying to put that object directly in the element. Either build some html from yourtagobject, eg<div>{tag.name}</div>or stringify it if you just want to display the whole object for whatever reason