😎 Discover cool tips and tricks for customization in our next Developer Deep Dive virtual event - sign up now!

Rich quotations in Portable Text

By Knut Melvær

Schemas for adding richer quotes within Portable Text

quote.js

// quote.js
export default {
  name: 'quote',
  type: 'object',
  title: 'Quote',
  fields: [
    {
      name: 'text',
      type: 'text', // <= This can also be a Portable Text field
      title: 'Text',
    },
    {
      name: 'author',
      type: 'string', // <= This could be a reference to an author document type, if you had that
      title: 'Author',
    },
    {
      name: 'url',
      type: 'url',
      title: 'URL',
      description: 'Source on the web', 
     }
  ]
}

portableText.js

// portableText.js
export default {
  name: 'portableText',
  type: 'array',
  title: 'Portable Text',
  of: [
    {
      type: 'block',
    },
    {
      type: 'quote',
    }
  ]
}

serializers.js (JSX)

// portableText.jsx
export const serializers = {
  type: {
    quote: ({ node: { text, author, url } }) => {
      return (
        <figure>
          <blockquote cite={url}>
            {text}
          </blockquote>
          {author && <figcaption>{author}</figcaption>}
        </figure>
      )
    }
  }
}

queries.groq

// Query for documents with more than 5 quotes in them. Given the portable text field is named “body”
*[count(body[_type == "quote"]) > 5]{
  _id,
 _type,
 "quotes": body[_type == "quote"].text
}

// Query for documents that has a quote by "Ursula K. Le Guin”
*["Ursula K. Le Guin" in body[_type == "quote"].author]{
  _id,
  _type,
  "quotes": body[_type == "quote"].text
}

This is an example of how to make a rich “quotation” block in Portable Text. It supports adding the author of the quote as well as an URL on the web.

You can customize this pattern to be more advanced by replacing the text field with a Portable Text field allowing for marks. The author field can also be a reference to another document type in cases where you have the quoted person as a resource in the Content Lake.

There's also an example of how to serialize this with JSX using the best HTML markup I could find (there might be better ways though).

This pattern also allows for querying your content lake by how many quotes there are, or by specific fields like quotes by a certain author.

Contributor

Other schemas by author