{"id":18471655,"url":"https://github.com/portabletext/react-portabletext","last_synced_at":"2025-05-14T16:02:46.575Z","repository":{"id":40610962,"uuid":"444015213","full_name":"portabletext/react-portabletext","owner":"portabletext","description":"Render Portable Text with React","archived":false,"fork":false,"pushed_at":"2025-03-10T05:21:39.000Z","size":5504,"stargazers_count":339,"open_issues_count":18,"forks_count":31,"subscribers_count":10,"default_branch":"main","last_synced_at":"2025-04-12T01:54:00.669Z","etag":null,"topics":["portable-text"],"latest_commit_sha":null,"homepage":"https://portabletext.github.io/react-portabletext/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/portabletext.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-01-03T10:06:54.000Z","updated_at":"2025-04-01T20:31:04.000Z","dependencies_parsed_at":"2023-09-28T17:26:33.971Z","dependency_job_id":"af15b5b5-41f7-41ec-abce-377cdb5cfe0c","html_url":"https://github.com/portabletext/react-portabletext","commit_stats":{"total_commits":127,"total_committers":10,"mean_commits":12.7,"dds":"0.25196850393700787","last_synced_commit":"49b69a9928a1c827fc50dfb79154ae021c688f00"},"previous_names":[],"tags_count":33,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/portabletext%2Freact-portabletext","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/portabletext%2Freact-portabletext/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/portabletext%2Freact-portabletext/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/portabletext%2Freact-portabletext/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/portabletext","download_url":"https://codeload.github.com/portabletext/react-portabletext/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248505873,"owners_count":21115354,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["portable-text"],"created_at":"2024-11-06T10:17:38.698Z","updated_at":"2025-04-12T01:54:28.165Z","avatar_url":"https://github.com/portabletext.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# @portabletext/react\n\n[![npm version](https://img.shields.io/npm/v/@portabletext/react.svg?style=flat-square)](https://www.npmjs.com/package/@portabletext/react)[![npm bundle size](https://img.shields.io/bundlephobia/minzip/@portabletext/react?style=flat-square)](https://bundlephobia.com/result?p=@portabletext/react)[![Build Status](https://img.shields.io/github/actions/workflow/status/portabletext/react-portabletext/main.yml?branch=main\u0026style=flat-square)](https://github.com/portabletext/react-portabletext/actions?query=workflow%3Atest)\n\nRender [Portable Text](https://portabletext.org/) with React.\n\nMigrating from [@sanity/block-content-to-react](https://www.npmjs.com/package/@sanity/block-content-to-react)? Refer to the [migration docs](https://github.com/portabletext/react-portabletext/blob/main/MIGRATING.md).\n\n## Table of contents\n\n- [Installation](#installation)\n- [Basic usage](#basic-usage)\n- [Styling](#styling-the-output)\n- [Customizing components](#customizing-components)\n- [Available components](#available-components)\n  - [types](#types)\n  - [marks](#marks)\n  - [block](#block)\n  - [list](#list)\n  - [listItem](#listItem)\n  - [hardBreak](#hardBreak)\n  - [unknown components](#unknownMark)\n- [Disable warnings / Handling unknown types](#disabling-warnings--handling-unknown-types)\n- [Rendering Plain Text](#rendering-plain-text)\n- [Typing Portable Text](#typing-portable-text)\n\n## Installation\n\n```\nnpm install --save @portabletext/react\n```\n\n## Basic usage\n\n```js\nimport {PortableText} from '@portabletext/react'\n\n\u003cPortableText\n  value={[/* array of portable text blocks */]}\n  components={/* optional object of custom components to use */}\n/\u003e\n```\n\n## Styling the output\n\nThe rendered HTML does not have any styling applied, so you will either render a parent container with a class name you can target in your CSS, or pass [custom components](#customizing-components) if you want to control the direct markup and CSS of each element.\n\n## Customizing components\n\nDefault components are provided for all standard features of the Portable Text spec, with logical HTML defaults. You can pass an object of components to use, both to override the defaults and to provide components for your custom content types.\n\nProvided components will be merged with the defaults. In other words, you only need to provide the things you want to override.\n\n**Note**: Make sure the object does not change on every render - eg do not create the object within a React component, or if you do, use `useMemo` to ensure referential identity between renders for better performance.\n\n```js\nconst myPortableTextComponents = {\n  types: {\n    image: ({value}) =\u003e \u003cimg src={value.imageUrl} /\u003e,\n    callToAction: ({value, isInline}) =\u003e\n      isInline ? (\n        \u003ca href={value.url}\u003e{value.text}\u003c/a\u003e\n      ) : (\n        \u003cdiv className=\"callToAction\"\u003e{value.text}\u003c/div\u003e\n      ),\n  },\n\n  marks: {\n    link: ({children, value}) =\u003e {\n      const rel = !value.href.startsWith('/') ? 'noreferrer noopener' : undefined\n      return (\n        \u003ca href={value.href} rel={rel}\u003e\n          {children}\n        \u003c/a\u003e\n      )\n    },\n  },\n}\n\nconst YourComponent = (props) =\u003e {\n  return \u003cPortableText value={props.value} components={myPortableTextComponents} /\u003e\n}\n```\n\n## Available components\n\nThese are the overridable/implementable keys:\n\n### `types`\n\nAn object of React components that renders different types of objects that might appear both as part of the input array, or as inline objects within text blocks - eg alongside text spans.\n\nUse the `isInline` property to check whether or not this is an inline object or a block.\n\nThe object has the shape `{typeName: ReactComponent}`, where `typeName` is the value set in individual `_type` attributes.\n\nExample of rendering a custom `image` object:\n\n```jsx\nimport {PortableText} from '@portabletext/react'\nimport urlBuilder from '@sanity/image-url'\nimport {getImageDimensions} from '@sanity/asset-utils'\n\n// Barebones lazy-loaded image component\nconst SampleImageComponent = ({value, isInline}) =\u003e {\n  const {width, height} = getImageDimensions(value)\n  return (\n    \u003cimg\n      src={urlBuilder()\n        .image(value)\n        .width(isInline ? 100 : 800)\n        .fit('max')\n        .auto('format')\n        .url()}\n      alt={value.alt || ' '}\n      loading=\"lazy\"\n      style={{\n        // Display alongside text if image appears inside a block text span\n        display: isInline ? 'inline-block' : 'block',\n\n        // Avoid jumping around with aspect-ratio CSS property\n        aspectRatio: width / height,\n      }}\n    /\u003e\n  )\n}\n\nconst components = {\n  types: {\n    image: SampleImageComponent,\n    // Any other custom types you have in your content\n    // Examples: mapLocation, contactForm, code, featuredProjects, latestNews, etc.\n  },\n}\n\nconst YourComponent = (props) =\u003e {\n  return \u003cPortableText value={somePortableTextInput} components={components} /\u003e\n}\n```\n\n### `marks`\n\nObject of React components that renders different types of marks that might appear in spans. Marks can either be simple \"decorators\" (eg emphasis, underline, italic) or full \"annotations\" which include associated data (eg links, references, descriptions).\n\nIf the mark is a decorator, the component will receive a `markType` prop which has the name of the decorator (eg `em`). If the mark is an annotation, it will receive both a `markType` with the associated `_type` property (eg `link`), and a `value` property with an object holding the data for this mark.\n\nThe component also receives a `children` prop that should (usually) be returned in whatever parent container component makes sense for this mark (eg `\u003ca\u003e`, `\u003cem\u003e`).\n\n```tsx\n// `components` object you'll pass to PortableText w/ optional TS definition\nimport {PortableTextComponents} from '@portabletext/react'\n\nconst components: PortableTextComponents = {\n  marks: {\n    // Ex. 1: custom renderer for the em / italics decorator\n    em: ({children}) =\u003e \u003cem className=\"text-gray-600 font-semibold\"\u003e{children}\u003c/em\u003e,\n\n    // Ex. 2: rendering a custom `link` annotation\n    link: ({value, children}) =\u003e {\n      const target = (value?.href || '').startsWith('http') ? '_blank' : undefined\n      return (\n        \u003ca href={value?.href} target={target} rel={target === '_blank' \u0026\u0026 'noindex nofollow'}\u003e\n          {children}\n        \u003c/a\u003e\n      )\n    },\n  },\n}\n```\n\n### `block`\n\nAn object of React components that renders portable text blocks with different `style` properties. The object has the shape `{styleName: ReactComponent}`, where `styleName` is the value set in individual `style` attributes on blocks (`normal` being the default).\n\n```jsx\n// `components` object you'll pass to PortableText\nconst components = {\n  block: {\n    // Ex. 1: customizing common block types\n    h1: ({children}) =\u003e \u003ch1 className=\"text-2xl\"\u003e{children}\u003c/h1\u003e,\n    blockquote: ({children}) =\u003e \u003cblockquote className=\"border-l-purple-500\"\u003e{children}\u003c/blockquote\u003e,\n\n    // Ex. 2: rendering custom styles\n    customHeading: ({children}) =\u003e (\n      \u003ch2 className=\"text-lg text-primary text-purple-700\"\u003e{children}\u003c/h2\u003e\n    ),\n  },\n}\n```\n\nThe `block` object can also be set to a single React component, which would handle block styles of _any_ type.\n\n### `list`\n\nObject of React components used to render lists of different types (`bullet` vs `number`, for instance, which by default is `\u003cul\u003e` and `\u003col\u003e`, respectively).\n\nNote that there is no actual \"list\" node type in the Portable Text specification, but a series of list item blocks with the same `level` and `listItem` properties will be grouped into a virtual one inside of this library.\n\n```jsx\nconst components = {\n  list: {\n    // Ex. 1: customizing common list types\n    bullet: ({children}) =\u003e \u003cul className=\"mt-xl\"\u003e{children}\u003c/ul\u003e,\n    number: ({children}) =\u003e \u003col className=\"mt-lg\"\u003e{children}\u003c/ol\u003e,\n\n    // Ex. 2: rendering custom lists\n    checkmarks: ({children}) =\u003e \u003col className=\"m-auto text-lg\"\u003e{children}\u003c/ol\u003e,\n  },\n}\n```\n\nThe `list` property can also be set to a single React component, which would handle lists of _any_ type.\n\n### `listItem`\n\nObject of React components used to render different list item styles. The object has the shape `{listItemType: ReactComponent}`, where `listItemType` is the value set in individual `listItem` attributes on blocks.\n\n```jsx\nconst components = {\n  listItem: {\n    // Ex. 1: customizing common list types\n    bullet: ({children}) =\u003e \u003cli style={{listStyleType: 'disclosure-closed'}}\u003e{children}\u003c/li\u003e,\n\n    // Ex. 2: rendering custom list items\n    checkmarks: ({children}) =\u003e \u003cli\u003e✅ {children}\u003c/li\u003e,\n  },\n}\n```\n\nThe `listItem` property can also be set to a single React component, which would handle list items of _any_ type.\n\n### `hardBreak`\n\nComponent to use for rendering \"hard breaks\", eg `\\n` inside of text spans.\n\nWill by default render a `\u003cbr /\u003e`. Pass `false` to render as-is (`\\n`)\n\n### `unknownMark`\n\nReact component used when encountering a mark type there is no registered component for in the `components.marks` prop.\n\n### `unknownType`\n\nReact component used when encountering an object type there is no registered component for in the `components.types` prop.\n\n### `unknownBlockStyle`\n\nReact component used when encountering a block style there is no registered component for in the `components.block` prop. Only used if `components.block` is an object.\n\n### `unknownList`\n\nReact component used when encountering a list style there is no registered component for in the `components.list` prop. Only used if `components.list` is an object.\n\n### `unknownListItem`\n\nReact component used when encountering a list item style there is no registered component for in the `components.listItem` prop. Only used if `components.listItem` is an object.\n\n## Disabling warnings / handling unknown types\n\nWhen the library encounters a block, mark, list or list item with a type that is not known (eg it has no corresponding component in the `components` property), it will by default print a console warning.\n\nTo disable this behavior, you can either pass `false` to the `onMissingComponent` property, or give it a custom function you want to use to report the error. For instance:\n\n```tsx\nimport {PortableText} from '@portabletext/react'\n\n\u003cPortableText\n  value={[/* array of portable text blocks */]}\n  onMissingComponent={false}\n/\u003e\n\n// or, pass it a function:\n\n\u003cPortableText\n  value={[/* array of portable text blocks */]}\n  onMissingComponent={(message, options) =\u003e {\n    myErrorLogger.report(message, {\n      // eg `someUnknownType`\n      type: options.type,\n\n      // 'block' | 'mark' | 'blockStyle' | 'listStyle' | 'listItemStyle'\n      nodeType: options.nodeType\n    })\n  }}\n/\u003e\n```\n\n## Rendering Plain Text\n\nThis module also exports a function (`toPlainText()`) that will render one or more Portable Text blocks as plain text. This is helpful in cases where formatted text is not supported, or you need to process the raw text value.\n\nFor instance, to render an OpenGraph meta description for a page:\n\n```tsx\nimport {toPlainText} from '@portabletext/react'\n\nconst MetaDescription = (myPortableTextData) =\u003e {\n  return \u003cmeta name=\"og:description\" value={toPlainText(myPortableTextData)} /\u003e\n}\n```\n\nOr to generate element IDs for headers, in order for them to be linkable:\n\n```tsx\nimport {PortableText, toPlainText, PortableTextComponents} from '@portabletext/react'\nimport slugify from 'slugify'\n\nconst LinkableHeader = ({children, value}) =\u003e {\n  // `value` is the single Portable Text block of this header\n  const slug = slugify(toPlainText(value))\n  return \u003ch2 id={slug}\u003e{children}\u003c/h2\u003e\n}\n\nconst components: PortableTextComponents = {\n  block: {\n    h2: LinkableHeader,\n  },\n}\n```\n\n## Typing Portable Text\n\nPortable Text data can be typed using the `@portabletext/types` package.\n\n### Basic usage\n\nUse `PortableTextBlock` without generics for loosely typed defaults.\n\n```ts\nimport {PortableTextBlock} from '@portabletext/types'\n\ninterface MySanityDocument {\n  portableTextField: (PortableTextBlock | SomeBlockType)[]\n}\n```\n\n### Narrow types, marks, inline-blocks and lists\n\n`PortableTextBlock` supports generics, and has the following signature:\n\n```ts\ninterface PortableTextBlock\u003c\n  M extends PortableTextMarkDefinition = PortableTextMarkDefinition,\n  C extends TypedObject = ArbitraryTypedObject | PortableTextSpan,\n  S extends string = PortableTextBlockStyle,\n  L extends string = PortableTextListItemType,\n\u003e {}\n```\n\nCreate your own, narrowed Portable text type:\n\n```ts\nimport {PortableTextBlock, PortableTextMarkDefinition, PortableTextSpan} from '@portabletext/types'\n\n// MARKS\ninterface FirstMark extends PortableTextMarkDefinition {\n  _type: 'firstMark'\n  // ...other fields\n}\n\ninterface SecondMark extends PortableTextMarkDefinition {\n  _type: 'secondMark'\n  // ...other fields\n}\n\ntype CustomMarks = FirstMark | SecondMark\n\n// INLINE BLOCKS\n\ninterface MyInlineBlock {\n  _type: 'myInlineBlock'\n  // ...other fields\n}\n\ntype InlineBlocks = PortableTextSpan | MyInlineBlock\n\n// STYLES\n\ntype TextStyles = 'normal' | 'h1' | 'myCustomStyle'\n\n// LISTS\n\ntype ListStyles = 'bullet' | 'myCustomList'\n\n// CUSTOM PORTABLE TEXT BLOCK\n\n// Putting it all together by specifying generics\n// all of these are valid:\n// type CustomPortableTextBlock = PortableTextBlock\u003cCustomMarks\u003e\n// type CustomPortableTextBlock = PortableTextBlock\u003cCustomMarks, InlineBlocks\u003e\n// type CustomPortableTextBlock = PortableTextBlock\u003cCustomMarks, InlineBlocks, TextStyles\u003e\ntype CustomPortableTextBlock = PortableTextBlock\u003cCustomMarks, InlineBlocks, TextStyles, ListStyles\u003e\n\n// Other BLOCKS that can appear inbetween text\n\ninterface MyCustomBlock {\n  _type: 'myCustomBlock'\n  // ...other fields\n}\n\n// TYPE FOR PORTABLE TEXT FIELD ITEMS\ntype PortableTextFieldType = CustomPortableTextBlock | MyCustomBlock\n\n// Using it in your document type\ninterface MyDocumentType {\n  portableTextField: PortableTextFieldType[]\n}\n```\n\n## License\n\nMIT © [Sanity.io](https://www.sanity.io/)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fportabletext%2Freact-portabletext","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fportabletext%2Freact-portabletext","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fportabletext%2Freact-portabletext/lists"}