How can I render data from Contentful's References field types? I am able to query the data in graphql and even use it in react to filter posts on my site with;
query TestQuery {
allContentfulPost {
edges {
node {
categories {
title
slug
}
}
}
}
}
But when I try render it to be displayed in the page it shows blank divs. I however am able to render all other field types, it's only the References field that's not working.
Reference field data in Contentful:

Reference field data fetched in graphql:

Simple test code:
import React from "react"
import { useStaticQuery, graphql } from "gatsby"
import Layout from "../components/Layout.js"
const TestPage = () => {
const data = useStaticQuery(graphql`
query TestQuery {
allContentfulPost {
edges {
node {
categories {
title
slug
}
}
}
}
}
`)
return (
<Layout>
{data.allContentfulPost.edges.map(({ node }) => {
return (
<div key={node.slug}>
{node.categories.title}
Reference fields should be here but their not ????
</div>
)
})}
</Layout>
)
}
export default TestPage
Reference field data Not rendering in React:

//
UPDATE:
I have done some trial and error with the GraphQL Fragments as suggested by Ferran below and I am able to view the data in localhost:8000/___graphql with;
query TestQuery {
allContentfulPost {
edges {
node {
categories {
... on ContentfulCategory {
title
slug
}
}
}
}
}
}
However, the divs rendered are still empty. Do I need to change the path for the data source "{node.categories.title}" in the return function for it to work? Do I maybe need to add something between "node" and "categories" to reference the "... on ContentfulCategory" added in the graphql query? If so, how should I write it? I have tried "{node.oncontentfulcategory.categories.title}" but that hasn't worked. Thanks again
import React from "react"
import { useStaticQuery, graphql } from "gatsby"
import Layout from "../components/Layout.js"
const TestPage = () => {
const data = useStaticQuery(graphql`
query TestQuery {
allContentfulPost {
edges {
node {
categories {
... on ContentfulCategory {
title
slug
}
}
}
}
}
}
`)
return (
<Layout>
{data.allContentfulPost.edges.map(({ node }) => {
return (
<div key={node.slug}>
{node.categories.title}
What path should I now use for the data source in the line above?
</div>
)
})}
</Layout>
)
}
export default TestPage