### Install Umbraco Rich Text Package
Source: https://github.com/charlie-tango/umbraco-rich-text/blob/main/README.md
Installs the `@charlietango/umbraco-rich-text` package using npm. This is the first step to integrate the rich text rendering functionality into your project.
```sh
npm install @charlietango/umbraco-rich-text
```
--------------------------------
### UmbracoRichText Component Usage
Source: https://context7.com/charlie-tango/umbraco-rich-text/llms.txt
Demonstrates how to use the UmbracoRichText component with custom node and block renderers, along with HTML attribute and style stripping configurations.
```APIDOC
## UmbracoRichText Component
### Description
Main component for rendering rich text content from Umbraco Content Delivery API. It transforms JSON-formatted rich text into React components.
### Method
React Component (Client-side rendering)
### Endpoint
N/A (Client-side component)
### Parameters
#### Props
- **data** (object) - Required - The JSON-formatted rich text data from Umbraco.
- **renderNode** (function) - Optional - A function to customize the rendering of specific HTML nodes (e.g., `p`, `a`, `img`). It receives a `RenderNodeContext` object.
- **renderBlock** (function) - Optional - A function to customize the rendering of Umbraco block elements. It receives a `RenderBlockContext` object.
- **htmlAttributes** (object) - Optional - An object where keys are HTML tag names and values are objects of HTML attributes to apply to those tags (e.g., `{ p: { className: "text-base" } }`).
- **stripStyles** (object) - Optional - An object to control the stripping of inline styles. Use `except` to specify tags for which styles should not be stripped (e.g., `{ except: ["img"] }`).
### Request Example
```jsx
import {
UmbracoRichText,
RenderBlockContext,
RenderNodeContext
} from "@charlietango/umbraco-rich-text";
import Image from "next/image";
import Link from "next/link";
// Custom node renderer
function renderNode({ tag, children, attributes, route, meta }: RenderNodeContext) {
switch (tag) {
case "a":
const href = route?.path || attributes.href;
return {children};
case "img":
return (
);
case "p":
const nodeInfo = meta();
const isFirstParagraph = !nodeInfo.previous;
return (
{children}
);
default:
return undefined; // Use default rendering
}
}
// Custom block renderer
function renderBlock({ content, settings }: RenderBlockContext) {
if (!content) return null;
switch (content.contentType) {
case "imageBlock":
return (
{content.properties.caption && (
{content.properties.caption as string}
)}
);
case "videoBlock":
return (
);
case "quoteBlock":
return (
{content.properties.quote as string}
{content.properties.author && (
— {content.properties.author as string}
)}
);
default:
return null;
}
}
function RichTextPage({ data }) {
return (
);
}
```
### Response
N/A (Component renders UI elements directly)
### Response Example
N/A
```
--------------------------------
### Render Umbraco Rich Text with Custom Nodes and Blocks in React
Source: https://github.com/charlie-tango/umbraco-rich-text/blob/main/README.md
Demonstrates how to use the `` component in a React application. It shows how to customize the rendering of specific HTML nodes (like `a` and `p`) and Umbraco content blocks (like `imageBlock`) by passing `renderNode` and `renderBlock` functions. It also illustrates setting default HTML attributes and stripping inline styles from specific tags.
```tsx
import {
UmbracoRichText,
RenderBlockContext,
RenderNodeContext,
} from "@charlietango/umbraco-rich-text";
import Image from "next/image";
import Link from "next/link";
function renderNode({ tag, children, attributes }: RenderNodeContext) {
switch (tag) {
case "a":
return {children};
case "p":
return (
{children}
);
default:
// Return `undefined` to render the default HTML node
return undefined;
}
}
function renderBlock({ content }: RenderBlockContext) {
switch (content?.contentType) {
// Switch over your Umbraco document types that can be rendered in the Rich Text blocks
case "imageBlock":
return ;
default:
return null;
}
}
function RichText({ data }) {
return (
);
}
```
--------------------------------
### Advanced Rendering with Additional Context in Umbraco Rich Text (TSX)
Source: https://context7.com/charlie-tango/umbraco-rich-text/llms.txt
Demonstrates passing extra context like image sizes, translations, and API configurations to render functions for image and link nodes. It also shows how to dynamically inject HTML attributes and handle link clicks.
```tsx
import {
UmbracoRichText,
RenderNodeContext,
RenderBlockContext
} from "@charlietango/umbraco-rich-text";
// Render function that accepts additional context
function renderNodeWithContext(
{ tag, children, attributes }: RenderNodeContext,
context: {
imageSizes: string;
translations: Record;
currentLocale: string;
}
) {
switch (tag) {
case "img":
return (
);
case "a":
// Add locale to internal links
const href = attributes.href as string;
const localizedHref = href.startsWith('/')
? `/${context.currentLocale}${href}`
: href;
return {children};
default:
return undefined;
}
}
function renderBlockWithContext(
block: RenderBlockContext,
context: { apiUrl: string; imageOptimization: boolean }
) {
if (!block.content) return null;
switch (block.content.contentType) {
case "imageBlock":
const imageUrl = block.content.properties.image?.url as string;
const optimizedUrl = context.imageOptimization
? `${context.apiUrl}/image-service?url=${encodeURIComponent(imageUrl)}&w=800&q=85`
: imageUrl;
return ;
default:
return null;
}
}
// Component that uses context-aware renderers
function RichTextWithContext({ data, locale, config }) {
const renderContext = {
imageSizes: "(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 800px",
translations: { readMore: "Read more", close: "Close" },
currentLocale: locale,
};
const blockContext = {
apiUrl: config.apiUrl,
imageOptimization: config.features.imageOptimization,
};
return (
renderNodeWithContext(node, renderContext)}
renderBlock={(block) => renderBlockWithContext(block, blockContext)}
stripStyles={true}
/>
);
}
// Example with dynamic attribute injection
function DynamicRichText({ content, className, onLinkClick }) {
return (
{
if (tag === "a") {
return (
{
e.preventDefault();
onLinkClick?.(attributes.href);
}}
>
{children}
);
}
return undefined;
}}
/>
);
}
```
--------------------------------
### Render Umbraco Rich Text with Custom Node and Block Rendering in React
Source: https://context7.com/charlie-tango/umbraco-rich-text/llms.txt
Demonstrates how to use the UmbracoRichText component to render JSON rich text data from Umbraco. It includes custom renderers for HTML nodes (like links and images) and Umbraco content blocks (imageBlock, videoBlock, quoteBlock). Customizations cover link handling, image display using Next.js Image, paragraph styling based on context, and structured rendering of various block types. It also showcases applying global HTML attributes and stripping specific inline styles.
```tsx
import {
UmbracoRichText,
RenderBlockContext,
RenderNodeContext
} from "@charlietango/umbraco-rich-text";
import Image from "next/image";
import Link from "next/link";
// Custom node renderer - override default HTML rendering
function renderNode({ tag, children, attributes, route, meta }: RenderNodeContext) {
switch (tag) {
case "a":
// Handle internal Umbraco links with route attribute
const href = route?.path || attributes.href;
return {children};
case "img":
return (
);
case "p":
// Access metadata about surrounding nodes
const nodeInfo = meta();
const isFirstParagraph = !nodeInfo.previous;
return (
{children}
);
default:
// Return undefined to use default rendering
return undefined;
}
}
// Custom block renderer - handle Umbraco document type blocks
function renderBlock({ content, settings }: RenderBlockContext) {
if (!content) return null;
switch (content.contentType) {
case "imageBlock":
return (
{content.properties.caption && (
{content.properties.caption as string}
)}
);
case "videoBlock":
return (
);
case "quoteBlock":
return (
{content.properties.quote as string}
{content.properties.author && (
— {content.properties.author as string}
)}
);
default:
return null;
}
}
// Component usage with all options
function RichTextPage({ data }) {
return (
);
}
```
--------------------------------
### Custom Rich Text Rendering with Additional Context
Source: https://github.com/charlie-tango/umbraco-rich-text/blob/main/README.md
Demonstrates how to customize the rendering of rich text nodes and blocks by passing additional context. This allows for passing props like image sizes or translations to custom render functions.
```jsx
import {
UmbracoRichText,
RenderBlockContext,
RenderNodeContext,
} from "@charlietango/umbraco-rich-text";
import Image from "next/image";
import Link from "next/link";
function renderNode(
{ tag, children, attributes }: RenderNodeContext,
extra: { sizes: string },
) {
switch (tag) {
case "img":
return ;
default:
return undefined;
}
}
function RichText({ data }) {
return (
{
return renderNode(node, { sizes: "720vw" });
}}
/>
);
}
```
--------------------------------
### Style Control with stripStyles in Umbraco Rich Text (TSX)
Source: https://context7.com/charlie-tango/umbraco-rich-text/llms.txt
Illustrates how to control the rendering of inline styles in Umbraco Rich Text components. Options include stripping all styles, stripping styles from specific tags, or preserving styles for certain elements like images.
```tsx
import { UmbracoRichText } from "@charlietango/umbraco-rich-text";
// Example 1: Remove all inline styles
function CleanRichText({ data }) {
return (
);
}
// Example 2: Strip styles from specific tags only
function SelectiveStyleStripping({ data }) {
return (
);
}
// Example 3: Strip all styles except specific tags
function PreserveImageStyles({ data }) {
return (
);
}
// Example 4: Combination with custom rendering
function FullyControlledRichText({ data }) {
return (
{
// Even without inline styles, you can add your own
if (tag === "p") {
return (
{children}
);
}
return undefined;
}}
/>
);
}
```
--------------------------------
### Augment UmbracoBlockItemModel with OpenAPI Types
Source: https://github.com/charlie-tango/umbraco-rich-text/blob/main/README.md
This TypeScript code snippet shows how to augment the `UmbracoBlockItemModel` interface within your project to correctly type Umbraco Rich Text blocks. It utilizes generated OpenAPI types from Umbraco's Delivery API Extensions and `openapi-typescript` to ensure accurate `contentType` and `properties` access within your `renderBlock` function.
```ts
// Import the `components` generated by OpenAPI TypeScript.
import { components } from "./umbraco-openapi";
// Define the intermediate interface
type ApiBlockItemModel = components["schemas"]["ApiBlockItemModel"];
declare module "@charlietango/umbraco-rich-text" {
interface UmbracoBlockItemModel extends ApiBlockItemModel {}
}
```
--------------------------------
### Augment Umbraco Block Types with OpenAPI Schemas (TypeScript)
Source: https://context7.com/charlie-tango/umbraco-rich-text/llms.txt
Extends the UmbracoBlockItemModel interface with types generated from an OpenAPI schema. This allows TypeScript to provide full type safety when accessing properties of Umbraco content blocks within your components. Ensure you generate your OpenAPI types using a tool like openapi-typescript.
```typescript
// types/umbraco-rich-text.d.ts
// Generate OpenAPI types using: npx openapi-typescript https://your-site.com/umbraco/swagger/v1/swagger.json -o types/umbraco-openapi.d.ts
import { components } from "./umbraco-openapi";
// Augment the library's block type with your Umbraco API schema
type ApiBlockItemModel = components["schemas"]["ApiBlockItemModel"];
declare module "@charlietango/umbraco-rich-text" {
interface UmbracoBlockItemModel extends ApiBlockItemModel {}
}
// Now use fully-typed blocks in your component
import { RenderBlockContext } from "@charlietango/umbraco-rich-text";
function renderBlock({ content, settings }: RenderBlockContext) {
if (!content) return null;
// TypeScript now knows the exact shape of content.properties
// based on your Umbraco content types
switch (content.contentType) {
case "heroBlock":
// TypeScript validates these property names against your schema
return (
);
default:
return null;
}
}
```
--------------------------------
### Convert Rich Text to Plain Text with Options
Source: https://github.com/charlie-tango/umbraco-rich-text/blob/main/README.md
Converts Umbraco rich text elements to plain text. Supports options for returning only the first paragraph, truncating text by a maximum length with ellipsis, and ignoring specific HTML tags during conversion.
```typescript
import { richTextToPlainText } from "@charlietango/umbraco-rich-text";
const plainText = richTextToPlainText(richTextData);
// Just the first paragraph
const firstParagraph = richTextToPlainText(richTextData, {
firstParagraph: true,
});
// Just the first 100 characters, truncated at the nearest word with an ellipsis
const first100Characters = richTextToPlainText(richTextData, {
maxLength: 100,
});
// Ignore certain tags, skipping their content
const ignoreTags = richTextToPlainText(richTextData, {
ignoreTags: ["h1", "h2", "ol", "figure"],
});
```
--------------------------------
### Convert Umbraco Rich Text to Plain Text (TypeScript)
Source: https://context7.com/charlie-tango/umbraco-rich-text/llms.txt
Converts Umbraco rich text JSON data into a plain text string. This function accepts options to extract only the first paragraph, limit the maximum length of the output, and ignore specific HTML tags. It's useful for generating SEO meta descriptions, previews, or simply cleaning up content.
```tsx
import { richTextToPlainText } from "@charlietango/umbraco-rich-text";
import type { RichTextElementModel } from "@charlietango/umbraco-rich-text";
// Sample rich text data from Umbraco
const richTextData: RichTextElementModel = {
tag: "#root",
elements: [
{
tag: "h1",
attributes: {},
elements: [{ tag: "#text", text: "Welcome to Our Site" }]
},
{
tag: "p",
attributes: {},
elements: [
{ tag: "#text", text: "This is the first paragraph with important content. " },
{ tag: "strong", attributes: {}, elements: [{ tag: "#text", text: "Bold text" }] },
{ tag: "#text", text: " and more regular text." }
]
},
{
tag: "p",
attributes: {},
elements: [{ tag: "#text", text: "This is a second paragraph." }]
}
]
};
// Extract all text content
const fullText = richTextToPlainText(richTextData);
// Output: "Welcome to Our Site This is the first paragraph with important content. Bold text and more regular text. This is a second paragraph."
// Get only first paragraph for meta description
const metaDescription = richTextToPlainText(richTextData, {
firstParagraph: true,
maxLength: 160
});
// Output: "This is the first paragraph with important content. Bold text and more regular text."
// Generate preview text with length limit
const preview = richTextToPlainText(richTextData, {
maxLength: 100
});
// Output: "Welcome to Our Site This is the first paragraph with important content. Bold text and more..."
// Extract text while ignoring specific elements
const bodyOnly = richTextToPlainText(richTextData, {
ignoreTags: ["h1", "h2", "h3", "figure", "blockquote"]
});
// Output: "This is the first paragraph with important content. Bold text and more regular text. This is a second paragraph."
// Combine options for SEO meta description
const seoDescription = richTextToPlainText(richTextData, {
firstParagraph: true,
maxLength: 155,
ignoreTags: ["code", "pre"]
});
// Use in Next.js metadata
export async function generateMetadata({ params }) {
const content = await fetchUmbracoContent(params.slug);
return {
title: content.name,
description: richTextToPlainText(content.properties.bodyText, {
firstParagraph: true,
maxLength: 160
}),
};
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.