i am making a blog where the blog content is written using rich text editor before using rich text editor i used substring
to display first 100 characters but now since rich text from my api is coming as an array i cant show the initial lines of post.
i am using sanity for cms
import React, { useEffect, useState } from 'react'
import { Link } from "react-router-dom"
import { client } from '../../client'
import PortableText from "react-portable-text"
import BlockContent from "@sanity/block-content-to-react"
const Blog = () => {
const [blogs, setBlogs] = useState([])
useEffect(() => {
const query = '*[_type == "blog"] | order(publishedAt desc)'
client.fetch(query)
.then((data) => {
console.log('before',data[0])
setBlogs(data);
})
}, [])
return (
<div>
<div style={{marginTop: "3rem"}} className='center top-name'>
BLOGS
</div>
<div class="blog_post">
{blogs.map((blog, index) => (
<div key={index} class="container_copy2">
<Link
style={{textDecoration: "none"}}
to={`/blog/${blog.slug.current}`}>
<div>
<h1 class="blog-title">{blog.title}</h1>
<p class="blog-content">
<BlockContent
blocks={blog.content}
projectId= {process.env.REACT_APP_SANITY_PROJECT_ID}
dataset="production"
/>
</p>
</div>
</Link>
<hr style={{color: "white", width: "500px", opacity: "0.2", marginTop: "2rem", marginBottom: "0px"}} />
</div>
))}
</div>
</div>
)
i tried using substring again but since its an array it wont work
2
Answers
using the serializers prop to customize the rendering of the block type then wrapping the text content of the block in a p tag with a class of blog-content and using substring(0, 100) to display only the first 100 characters of the block’s text content.
If you want to do this on the client side, then another option is CSS line-clamp. This way, you won’t need to compute the character count and the browser will do it automatically for you.