Skip to content

Instantly share code, notes, and snippets.

@SebbeJohansson
Created May 10, 2023 08:48
Show Gist options
  • Select an option

  • Save SebbeJohansson/467244f90bec9e3e8994d4bacd00f794 to your computer and use it in GitHub Desktop.

Select an option

Save SebbeJohansson/467244f90bec9e3e8994d4bacd00f794 to your computer and use it in GitHub Desktop.
Storyblok Richtext formatting for proper translated internal links and prevents "Cannot read properties of undefined (reading 'color')" error.
import { renderRichText } from '@storyblok/nuxt-2';
import { toInternalLink } from '~/utils/storyblok/link-helpers';
export const renderStoryblokRichText = (richText, channelRootPath) => {
const richTextJson = JSON.stringify(richText);
const richTextObject = JSON.parse(richTextJson);
// This functions goes through the nodes and removes empty links and properly handles internal links.
const loopThroughNodes = (node) => {
const localNode = { ...node };
localNode.content.map((content) => {
if (content.content) {
content = loopThroughNodes(content);
}
if (content.marks) {
content.marks = content.marks
.filter((mark) => mark.type !== 'link' || (mark.type === 'link' && !!mark.attrs)) // Remove empty links
.map((mark) => {
// Prevents issue with marks without attributes.
mark.attrs = mark.attrs ?? {};
if (mark.type === 'link' && mark.attrs?.href) {
mark.attrs.href =
toInternalLink(mark.attrs.story?.full_slug, channelRootPath) ??
mark.attrs.story?.url ??
mark.attrs.href;
}
return mark;
});
}
return content;
});
return localNode;
};
const rendered = renderRichText(loopThroughNodes(richTextObject));
return rendered;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment