Skip to content

Instantly share code, notes, and snippets.

@cpitt
Created July 24, 2020 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpitt/70b8dcc3dafb4419005a92ece8b8b640 to your computer and use it in GitHub Desktop.
Save cpitt/70b8dcc3dafb4419005a92ece8b8b640 to your computer and use it in GitHub Desktop.
translate conentful document into material-ui components
import {
documentToReactComponents,
Options,
} from '@contentful/rich-text-react-renderer';
import { Document, BLOCKS, INLINES } from '@contentful/rich-text-types';
import { Typography, Divider, Link } from '@material-ui/core';
/**
* a wrapper around documentToReactComponents that has material-ui component defaults
**/
function documentToMUIComponents(
richTextDocument: Document,
options?: Options,
) {
const defaultOptions: Options = {
renderNode: {
[BLOCKS.HEADING_1]: (_node, children) => (
<Typography variant="h1">{children}</Typography>
),
[BLOCKS.HEADING_2]: (_node, children) => (
<Typography variant="h2">{children}</Typography>
),
[BLOCKS.HEADING_3]: (_node, children) => (
<Typography variant="h3">{children}</Typography>
),
[BLOCKS.HEADING_4]: (_node, children) => (
<Typography variant="h4">{children}</Typography>
),
[BLOCKS.HEADING_5]: (_node, children) => (
<Typography variant="h5">{children}</Typography>
),
[BLOCKS.HEADING_6]: (_node, children) => (
<Typography variant="h6">{children}</Typography>
),
[BLOCKS.HR]: (_node, children) => <Divider />,
[BLOCKS.QUOTE]: (node, children) => (
<Typography variant="body2" align="center" paragraph>
{children}
</Typography>
),
[BLOCKS.PARAGRAPH]: (_node, children) => (
<Typography variant="body1" paragraph>
{children}
</Typography>
),
[INLINES.HYPERLINK]: (node, children) => (
<Link href={node.data.uri}>{children}</Link>
),
},
};
return documentToReactComponents(richTextDocument, {
...defaultOptions,
...options,
});
}
export default documentToMUIComponents;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment