Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

Creating a React/Gatsby component to limit text to ~190 characters from an array field

4 replies
Last updated: Apr 2, 2020
I’m attempting to create a
<BlockExcerpt>
component (React/Gatsby) that takes the contents of my
_rawBody
field (array type) and output plain text that is limited to ~190 characters. I’m struggling to properly parse the nested arrays and output them with proper spacing. See code in thread.
Apr 2, 2020, 2:34 AM
const BlockExcerpt = ({ blocks }) => {
  // console.log(blocks)

  const blockText = blocks.map(block => {
    return block.children.map(blockPart => {
      return blockPart.text
    })
  });

  const flat = blockText.flat(2)
  const joined = flat.join("")
  const truncated = joined.substring(0,190)
  return <p className={typo.p}>{truncated}&hellip;</p>
}

export default BlockExcerpt
Apr 2, 2020, 2:34 AM
Since I’m flattening and joining the array, marks have proper spacing but paragraphs have no spacing.
https://d.pr/free/i/2hDkgf
Apr 2, 2020, 2:38 AM
Apr 2, 2020, 2:44 AM
Apr 2, 2020, 4:27 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?