npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@madebyconnor/rich-text-to-jsx

v2.3.0

Published

Opinionated JSX renderer for the Contentful rich text field type.

Downloads

10,540

Readme

rich-text-to-jsx

Opinionated JSX renderer for the Contentful Rich Text field type

NPM version Continuous Integration Code coverage License MIT Contributor Covenant


rich-text-to-jsx is inspired by markdown-to-jsx. Notably, this package offers the following benefits:

Any HTML tags (corresponding to node types) rendered by the compiler can be overridden to include additional props or even a different React component entirely. Embedded entries and assets can be rendered using different components depending on whether they are inline, blocks or hyperlinks. The rendering function can be customized. All this clocks in at around 4 kB gzipped.

⚠️ Requires React >= 16.0.0. Some features depend on a specific content structure: entry and asset links need to be resolved and the content localized. If this is a deal breaker for you, have a look at the official rich-text-react-renderer package.

Installation

Install @madebyconnor/rich-text-to-jsx with your favorite package manager.

# npm
npm i @madebyconnor/rich-text-to-jsx

Getting started

@madebyconnor/rich-text-to-jsx exports a React component for easy JSX composition:

import React from 'react';
import { render } from 'react-dom';
import RichText from '@madebyconnor/rich-text-to-jsx';

const richText = {
  data: {},
  content: [
    {
      data: {},
      content: [
        {
          data: {},
          marks: [],
          value: 'Hello world!',
          nodeType: 'text',
        },
      ],
      nodeType: 'paragraph',
    },
  ],
  nodeType: 'document',
};

render(<RichText richText={richText} />, document.body);

/*
    renders:

    <p>Hello world!</p>
 */

Parsing Options

options.overrides - Override any node's representation

Pass the options.overrides prop to the compiler or the <RichText> component to seamlessly revise the rendered representation of any node type. You can choose to change the component itself, add/change props, or both.

import React from 'react';
import { render } from 'react-dom';
import RichText from '@madebyconnor/rich-text-to-jsx';
import { BLOCKS } from '@contentful/rich-text-types';

// Surprise, it's a div instead!
const MyParagraph = ({ children, ...props }) => (
  <div {...props}>{children}</div>
);

render(
  <RichText
    richText={{ ... }}
    overrides={{
      [BLOCKS.PARAGRAPH]: {
        component: MyParagraph,
        props: {
          className: 'foo'
        }
      }
    }}
  />,
  document.body
);

/*
    renders:

    <div class="foo">
        Hello World
    </div>
 */

If you only wish to provide a component override, a simplified syntax is available:

const overrides = {
  [BLOCKS.PARAGRAPH]: MyParagraph,
};

// or by HTML tag

const overrides = {
  p: MyParagraph,
};

Any conflicts between passed props and the specific properties above will be resolved in favor of @madebyconnor/rich-text-to-jsx's code. classNames are merged automatically. The uri prop on INLINES.HYPERLINK nodes is renamed to href for convenience.

Entries

For embedded entries, you need to specify the component for each possible node type and content type. This enables you to use different components for the same entry, depending on whether it is rendered inline, as a block or as a hyperlink. The component receives the data in node.data.target as props.

Let's say you have an entry of the content type page. When the page entry is referenced as a hyperlink, an anchor should be rendered. When the page entry is embedded as a block, a preview with its title and subtitle should be rendered. Here's how you could achieve that:

const PageLink = ({ slug, children }) => <a href={slug}>{children}</a>;
const PagePreview = ({ title, summary, className }) => (
  <div className={className}>
    <h2>{title}</h2>
    <p>{summary}</p>
  </div>
);

const overrides = {
  [INLINES.ENTRY_HYPERLINK]: {
    page: PageLink,
  },
  [BLOCKS.EMBEDDED_ENTRY]: {
    page: {
      component: PagePreview,
      props: {
        className: 'page-preview',
      },
    },
  },
};

Assets

Embedded assets work very similar to entries. However, assets don't have a content type, so instead you can define custom components for each mime type group. Here's an example:

const ImageLink = ({ file, title }) => (
  <a href={file.url} download>
    {title}
  </a>
);
const Image = ({ file, title, className }) => (
  <img className={className} src={file.url} alt={title} />
);

const overrides = {
  [INLINES.ENTRY_HYPERLINK]: {
    image: ImageLink,
  },
  [BLOCKS.EMBEDDED_ENTRY]: {
    image: {
      component: Image,
      props: {
        className: 'image--fullwidth',
      },
    },
  },
};

By default, images, videos, and audio files are rendered with the appropriate HTML5 elements when embedded as blocks and as download links when embedded inline or as hyperlinks.

options.createElement - Custom React.createElement behavior

Sometimes, you might want to override the React.createElement default behavior to hook into the rendering process before the JSX gets rendered. This might be useful to add extra children or modify some props based on runtime conditions. The function mirrors the React.createElement function, so the params are type, [props], [...children]:

import React from 'react';
import { render } from 'react-dom';
import RichText from '@madebyconnor/rich-text-to-jsx';

render(
  <RichText
    richText={{ ... }}
      createElement={(type, props, children) => (
        <div className="parent">
          {React.createElement(type, props, children)}
        </div>
      )}
  />,
  document.body
);

/*
    renders:

    <div className="parent">
        <p>Hello world!</p>
    </div>
 */

Using the compiler directly

If desired, the compiler function is a named export on the @madebyconnor/rich-text-to-jsx module:

import React from 'react';
import { render } from 'react-dom';
import { richTextToJsx } from '@madebyconnor/rich-text-to-jsx';

const richText = {{ ... }}

richTextToJsx(richText);

It accepts the following arguments:

richTextToJsx(richText: string, options: object?)

Getting the smallest possible bundle size

Many development conveniences are placed behind process.env.NODE_ENV !== "production" conditionals. When bundling your app, it's a good idea to replace these code snippets such that a minifier (like uglify) can sweep them away and leave a smaller overall bundle.

Here are instructions for some of the popular bundlers:

Usage with Preact

Everything will work just fine! Simply Alias react to preact-compat like you probably already are doing.

Changelog

See GitHub Releases.