• This repository has been archived on 12/Apr/2023
  • Stars
    star
    162
  • Rank 232,284 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Deprecated in favor of @portabletext/react

block-content-to-react

Render an array of block text from Sanity with React or React Native.

⚠️ Note: This package is deprecated. We recommend migrating to its modernized successor, @portabletext/react. Refer to the migration documentation for how to do the switch.

Installing

npm install --save @sanity/block-content-to-react

Usage

const React = require('react')
const ReactDOM = require('react-dom')
const BlockContent = require('@sanity/block-content-to-react')
const client = require('@sanity/client')({
  projectId: '<your project id>',
  dataset: '<some dataset>',
  apiVersion: '2021-03-25',
  useCdn: true,
})

const serializers = {
  types: {
    code: (props) => (
      <pre data-language={props.node.language}>
        <code>{props.node.code}</code>
      </pre>
    ),
  },
}

client.fetch('*[_type == "article"][0]').then((article) => {
  ReactDOM.render(
    <BlockContent blocks={article.body} serializers={serializers} />,
    document.getElementById('root')
  )
})

PropTypes

  • className - When more than one block is given, a container node has to be created. Passing a className will pass it on to the container. Note: see renderContainerOnSingleChild.
  • renderContainerOnSingleChild - When a single block is given as input, the default behavior is to not render any container. If you always want to render the container, pass true.
  • serializers - Specifies the React components to use for rendering content. Merged with default serializers.
  • serializers.types - Serializers for block types, see example above
  • serializers.marks - Serializers for marks - data that annotates a text child of a block. See example usage below.
  • serializers.list - React component to use when rendering a list node
  • serializers.listItem - React component to use when rendering a list item node
  • serializers.hardBreak - React component to use when transforming newline characters to a hard break (<br/> by default, pass false to render newline character)
  • serializers.container - Serializer for the container wrapping the blocks
  • serializers.unknownType - Override the default serializer for blocks of unknown type, if ignoreUnknownTypes is set to false (the default).
  • serializers.unknownMark - Override the default serializer for marks of unknown type. Defaults to a span without any styling.
  • imageOptions - When encountering image blocks, this defines which query parameters to apply in order to control size/crop mode etc.
  • ignoreUnknownTypes - By default (or when setting this property explicitly to true) it will output a hidden <div> with a warning. By setting this property to false, the renderer will throw an error when encountering unknown block types. The behavior of the unknown type rendering can be customized by specifying a serializer with serializers.unknownType.

In addition, in order to render images without materializing the asset documents, you should also specify:

  • projectId - The ID of your Sanity project.
  • dataset - Name of the Sanity dataset containing the document that is being rendered.

Examples

Rendering custom marks

const input = [
  {
    _type: 'block',
    children: [
      {
        _key: 'a1ph4',
        _type: 'span',
        marks: ['s0m3k3y'],
        text: 'Sanity',
      },
    ],
    markDefs: [
      {
        _key: 's0m3k3y',
        _type: 'highlight',
        color: '#E4FC5B',
      },
    ],
  },
]

const highlight = (props) => {
  return <span style={{backgroundColor: props.mark.color}}>{props.children}</span>
}

ReactDOM.render(
  <BlockContent
    // Array of portable text blocks
    blocks={input}
    // Custom serializers for marks, blocks
    serializers={{marks: {highlight}}}
  />,
  document.body
)

Specifying image options

<BlockContent
  blocks={input}
  imageOptions={{w: 320, h: 240, fit: 'max'}}
  projectId="myprojectid"
  dataset="mydataset"
/>

Customizing the default serializer for block-type

This code snippet first checks for a heading style (h1, h2, h3, and so on), and returns a React-element with a custom classname that includes the heading level. It has also defined a how blocks with a blockquote style should be rendered, adding a hyphen in front of it's children. If the block doesn't have any customBlocks defined, it will fall back on the default serializers (BlockContent.defaultSerializers.types.block(props)).

const BlockRenderer = (props) => {
  const {style = 'normal'} = props.node

  if (/^h\d/.test(style)) {
    const level = style.replace(/[^\d]/g, '')
    return React.createElement(style, {className: `heading-${level}`}, props.children)
  }

  if (style === 'blockquote') {
    return <blockquote>- {props.children}</blockquote>
  }

  // Fall back to default handling
  return BlockContent.defaultSerializers.types.block(props)
}

ReactDOM.render(
  <BlockContent blocks={input} serializers={{types: {block: BlockRenderer}}} />,
  document.body
)

Usage with React Native

React Native support is experimental, but should work. Built-in serializers render using React Native elements instead of HTML tags when React Native is detected, and serializers can be specified as you normally would.

Since there are fewer built-in elements in React Native, elements such as lists are implemented using plain (text) views, styled to look rougly like the HTML variant. You'll probably want to customize most of the serializers when using React Native, since styling is not handled in a cascading fashion.

License

MIT-licensed. See LICENSE.

More Repositories

1

sanity

Sanity Studio – Rapidly configure content workspaces powered by structured content
TypeScript
4,364
star
2

litter

Litter is a pretty printer library for Go data structures to aid in debugging and testing.
Go
1,437
star
3

next-sanity

Sanity.io toolkit for Next.js
TypeScript
667
star
4

nextjs-blog-cms-sanity-v3

A Next.js Blog with a Native Authoring Experience
TypeScript
392
star
5

GROQ

Specification for GROQ - The Query Language for JSON
JavaScript
380
star
6

hydrogen-sanity-demo

A starter for Hydrogen + Sanity projects
TypeScript
334
star
7

example-company-website-gatsby-sanity-combo

This is an example company website using Gatsby and Sanity in combination.
JavaScript
270
star
8

groq-js

JavaScript implementation of GROQ, the query language for JSON
TypeScript
250
star
9

mendoza

Differ for structured documents (JSON)
Go
234
star
10

template-nextjs-personal-website

A Next.js Personal Website with a Native Authoring Experience
TypeScript
233
star
11

example-frontend-next-js

An example of a Sanity powered frontend using Next.js
JavaScript
212
star
12

groq-cli

Run GROQ in your command line
JavaScript
198
star
13

gatsby-source-sanity

Gatsby source plugin for building websites using Sanity.io as a backend.
TypeScript
195
star
14

sanity-recipes

A collection of recipies / snippets / frequently asked questions about Sanity.io
JavaScript
159
star
15

sanity-plugin-media

Asset management plugin for Sanity
TypeScript
153
star
16

sanity-shopify-studio

An example Sanity Studio configured for headless Shopify projects.
TypeScript
144
star
17

sanity-template-nextjs-landing-pages

A Sanity powered landing page builder in Next.js for https://sanity.io/create
JavaScript
142
star
18

sanity-template-nextjs-clean

A clean Next.js template with a native authoring experience
TypeScript
141
star
19

squizzy

Quizzes with Squizzy the Squid!
JavaScript
139
star
20

tutorial-sanity-blog-react-next

Front-end code for the Sanity, React, Next.js tutorial.
TypeScript
136
star
21

document-internationalization

Create unique translations of a document based on its language, joined by a shared reference document
TypeScript
130
star
22

ui

UI building blocks for Sanity.
TypeScript
130
star
23

sanity-template-nextjs-app-router-personal-website

A Next.js Personal Website with a Native Authoring Experience. Uses app router.
112
star
24

preview-kit

General purpose live previews, like next-sanity
TypeScript
109
star
25

sanity-template-astro-clean

Clean starter template with Astro
Astro
105
star
26

sanity-template-kitchen-sink

A collection of demo examples
JavaScript
103
star
27

example-ecommerce-snipcart-vue

The Transglobal Candy Store: Sample front-end for the Sanity.io e-commerce schema with vue.js, nuxt.js, and snipcart
Vue
100
star
28

sanity-template-gatsby-blog

A Sanity powered Gatsby blog for https://www.sanity.io/create
JavaScript
99
star
29

sanity-template-nextjs-blog-comments

JavaScript
83
star
30

sanity-template-nextjs-ecommerce

CSS
76
star
31

orderable-document-list

Drag-and-drop Document Ordering without leaving the Editing surface
TypeScript
75
star
32

plugin-kit

Enhanced Sanity.io plugin development experience.
TypeScript
74
star
33

client

JavaScript client for retrieving, creating and patching data from Sanity.io
TypeScript
73
star
34

community-studio

Sanity Community Management Studio
TypeScript
73
star
35

example-frontend-vue-js

An example of a Sanity powered frontend using Vue.js
Vue
72
star
36

content-source-maps

Specification for the Content Source Maps standard. Used to power Visual Editing experiences.
72
star
37

sanity-template-gatsby-portfolio

A Gatsby portfolio site powered by Sanity for https://www.sanity.io/create
JavaScript
70
star
38

sanity-astro

TypeScript
65
star
39

sanity-algolia

Utilities for indexing Sanity documents in Algolia
TypeScript
61
star
40

github-action-sanity

Dockerfile
55
star
41

demo-course-platform

An example Studio and Front End demonstrating different strategies for localization with Sanity.io
TypeScript
54
star
42

sanity-plugin-mux-input

An input component that integrates Sanity Studio with MUX.com video encoding/hosting service.
TypeScript
51
star
43

sanity-plugin-graph-view

A tool for Sanity Studio to graph your content and see changes in real-time.
TypeScript
49
star
44

sanity-template-sveltekit-clean

Clean starter template with SvelteKit
Svelte
48
star
45

sanity-plugin-markdown

Markdown support in the Sanity Studio
TypeScript
48
star
46

next-recipe-app

CSS
48
star
47

sanity-template-nuxt-clean

Clean starter template with Nuxt
Vue
48
star
48

sanity-plugin-iframe-pane

Display any URL in a View Pane, along with helpful buttons to copy the URL, display a mobile size, reload the iframe or open in a new tab
TypeScript
47
star
49

hydrogen-sanity

A Sanity toolkit for Hydrogen
TypeScript
47
star
50

sanity-template-nuxt-events

A Sanity powered Conference site in Vue / Nuxt for https://www.sanity.io/create
Vue
46
star
51

netlify-form-sanity

How to use Netlify Forms and Functions to submit data to Sanity.io
HTML
46
star
52

startup-starter-kit

The Structured Content Startup Starter Kit
JavaScript
45
star
53

demo-custom-workflow

A demonstration of a custom content publishing workflow using Sanity.
HTML
44
star
54

sanity-template-sapper-blog

JavaScript
44
star
55

react-rx

React + RxJS = <3
TypeScript
43
star
56

image-url

Tools to generate image urls from Sanity content
TypeScript
43
star
57

sanity-plugin-internationalized-array

A plugin to register array fields with a custom input component to store field values in multiple languages, queryable by using the language ID as an array `_key`.
TypeScript
43
star
58

hierarchical-document-list

Plugin for editing hierarchical references in the Sanity studio.
TypeScript
41
star
59

demo-marketing-site-nextjs

TypeScript
40
star
60

gatsby-portfolio-preview-poc

Gatsby Portfolio Preview POC
JavaScript
40
star
61

groq-store

In-memory GROQ store. Streams all available documents from Sanity into an in-memory database for local querying.
TypeScript
40
star
62

sanity-studio-secrets

Hooks and chrome for handling secrets in plugins
TypeScript
39
star
63

sanity-template-nextjs-event-starter

Fully customizable starter kit for your virtual event.
TypeScript
39
star
64

vscode-sanity

Visual Studio Code extension for developing applications powered by Sanity.io
TypeScript
38
star
65

sanity-plugin-seo-pane

Run Yoast's SEO review tools using Sanity data, inside a List View Pane.
TypeScript
38
star
66

example-app-react-native

Sanity + React Native app example
JavaScript
38
star
67

themer

Experimental, creates Studio v3 themes
TypeScript
37
star
68

table

Table schema type and input component for Sanity Studio
TypeScript
37
star
69

sanity-template-eleventy-blog

Minimal blog with Eleventy and Sanity
JavaScript
37
star
70

swift-sanity

Swift
36
star
71

demo-ecommerce

TypeScript
36
star
72

sanity-template-vercel-visual-editing

TypeScript
36
star
73

webhook-toolkit

Toolkit for dealing with GROQ-powered webhooks delivered by Sanity.io
TypeScript
35
star
74

mendoza-js

Mendoza decoder in TypeScript
TypeScript
35
star
75

sanity-plugin-dashboard-widget-vercel

TypeScript
33
star
76

sanity-template-svelte-kit

A minimal, fully customizable SvelteKit front-end powered by Sanity.io data.
JavaScript
32
star
77

block-content-to-markdown

Transform Sanity block content to Markdown
JavaScript
31
star
78

visual-editing

TypeScript
31
star
79

cross-dataset-duplicator

Empower content editors to migrate Documents and Assets between Sanity Projects and Datasets from inside Sanity Studio.
TypeScript
31
star
80

sanity-plugin-dashboard-widget-netlify

Sanity Studio Dashboard Widget for triggering Netlify builds
TypeScript
29
star
81

sanity-php

PHP library for retrieving, creating and patching data from Sanity.io
PHP
28
star
82

sanity-plugin-scheduled-publishing

Schedule documents for future publishing
TypeScript
28
star
83

sanity-template-remix-clean

Clean starter template with Remix
TypeScript
28
star
84

get-it

Composable HTTP request library for node and browsers
TypeScript
26
star
85

contentful-to-sanity

Migrate from Contentful to Sanity
TypeScript
26
star
86

sanity-template-gridsome-blog

A Sanity powered Gridsome blog for sanity.io/create
JavaScript
25
star
87

asset-utils

Reusable utility functions for dealing with image and file assets in Sanity
TypeScript
24
star
88

pkg-utils

Simple utilities for modern npm packages.
TypeScript
24
star
89

sanity-plugin-hotspot-array

A configurable Custom Input for Arrays that will add and update items by clicking on an Image
TypeScript
23
star
90

dashboard

Tool for rendering dashboard widgets
TypeScript
23
star
91

jsonwebtoken-esm

jsonwebtoken wrapper that provides esm support
JavaScript
22
star
92

create-react-app-blog

JavaScript
22
star
93

demo-media-site-nextjs

A demo template for a content-driven site with longform content and newsletter capability
TypeScript
21
star
94

sanity-mux-player

Play videos in the frontend uploaded with the MUX Sanity plugin
JavaScript
21
star
95

sanity-plugin-shopify-assets

TypeScript
21
star
96

code-input

Code input and schema for Sanity Studio
TypeScript
21
star
97

sanity-nextjs-vercel-example

A bare bones example of a Vercel-deployable project with a Next.js frontend and a Sanity Studio on /studio
JavaScript
21
star
98

locales

A repository of user-contributed locale/language packs for Sanity Studio
TypeScript
21
star
99

block-content-to-html

Deprecated in favor of @portabletext/to-html
JavaScript
21
star
100

sanity-plugin-cloudinary

Official plugin for integrating Sanity Studio with Cloudinary
TypeScript
20
star