I'm developing a blog using Strapi and React and the articles in the blog have multiple categories, I get a GraphQL query from Strapi like this
(blogpostObject){
"categories": [
{
"name": "Category 1"
},
{
"name": "Category 2"
},
],
}
I want to access the "name" value of each category and display them separated by commas each of them with an <a>
tag with a link to another page.
so far I only came up with this solution
queryData.map(article => (
article.categories.map(category => category.name).toString().replace(/,/g, `, `)
this will render: "Category 1, Category 2", but I don't know how to add the <a>
tag to each of them from here.
EDIT: I'm using Gatsby to build this project, so I'm using React Link component to handle internal links.
This is a sample GraphQL response
{
"data": {
"allStrapiArticle": {
"nodes": [
{
"title": "This is my second article",
"slug": "this-is-my-second-article",
"content": " Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"id": "Article_2",
"author": {
"name": "Average Joe"
},
"categories": [
{
"name": "Category 1"
}
],
"created_at": "Wednesday, June 24th 2020"
}
import React from "react";
// this data would come from graphql instead
const data = {
allStrapiArticle: {
nodes: [
{
title: "This is my second article",
slug: "this-is-my-second-article",
content: " Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
id: "Article_2",
author: {
name: "Average Joe"
},
categories: [
{
name: "Category 1"
},
{
name: "Category 2"
},
{
name: "Category 3"
}
],
created_at: "Wednesday, June 24th 2020"
}
]
}
};
const App = () => {
return (
<div>
{data.allStrapiArticle.nodes.map(node => {
return node.categories.map((category, index) => {
return (
<>
<a href="/">{category.name}</a>
{index < node.categories.length - 1 && ", "}
</>
);
});
})}
</div>
);
};
export default App;