✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

How to call blog post categories in HTML in a React project

5 replies
Last updated: Dec 17, 2021
Hey guys,
I’m building a blog using auto-generated Blog (schema).
How do I get blog post
categories and category and call them in div ?
/sidangkalam/src/pages/Homepage.js

import { Carousel } from 'react-bootstrap';

import { useState, useEffect } from "react"

import client from "../client"

import { Link } from 'react-router-dom';


export default function Homepage() {

const [posts, setPosts] = useState([])


useEffect(() => {

client.fetch(
``*[_type == "post"] {`

title,

slug,

body,

categories {

category -> {

title },

mainImage {

asset -> {

_id,

url

},

alt

}
`}``

).then((data) => setPosts(data)).catch(console.error)

}, [])

return (

<div>{post.categories.title}</div>

/sidangkalam/schemas/category.js


export default {

name: 'category',

title: 'Category',

type: 'document',

fields: [

{

name: 'title',

title: 'Title',

type: 'string',

},

{

name: 'description',

title: 'Description',

type: 'text',

},

],

}

Currently it gives me below error :

(anonymous function)
src/pages/Homepage.js:238

  235 |     alt={post.title}
  236 |   />
  237 |   
> 238 |   <span className="thumb-title">{post.categories.title} </span>
      | ^
  239 | </div>
  240 | <h5 className="font-weight-bold mt-3">
  241 | {post.title}

Dec 15, 2021, 3:43 AM
Thanks for your response
user M
but &lt;span className=“thumb-title”&gt;{post.categories.title}&lt;/span&gt; didn’t return anything.
How do you call it in html ?
😅
Dec 16, 2021, 2:49 PM
Thanks for your response but &lt;span className=“thumb-title”&gt;{post.categories.title}&lt;/span&gt; didn’t return anything.
How do you call it in html ?
😅
Dec 16, 2021, 2:49 PM
Hmm, are you sure your query is returning results? If you
console.log
it, what do you get?
Dec 16, 2021, 5:36 PM
Hmm, are you sure your query is returning results? If you
console.log
it, what do you get?
Dec 16, 2021, 5:36 PM
I had found solution for this one. Thanks!
Dec 17, 2021, 2:00 AM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?