Rendering Kentico Cloud linked content items with React components in Gatsby
Sunday, February 24, 2019
On Wednesday, 20th February, v3.0.0 of the Kentico Gatsby source plugin was released, with a key new feature.
The new version allows inline content items, assets and links to be transformed. The first approach is to use the Type Resolvers and rich text resolvers defined in the Kentico Cloud SDK.
This approach allows for simple conversion between the original data and HTML mark-up, however, this does not allow the use of React components. Due to this, you will lose any ability to use CSS-in-JS frameworks, anything within the React context, any state data etc. One of the key restrictions specific to Gatsby is that you cannot use the Gatsby Link component, meaning any internal links will result in a full-page reload.
So, in order to have more control over the result and remove these restrictions, we need to somehow transform the HTML from Kentico Cloud into React components and then replace the embedded items with our own custom React components.
Firstly, we need to convert that HTML code into React components. I’ve opted to use the html-react-parser library for this.
Great! But it looks exactly how it did before, and the inline items aren’t transformed.
When we parse the above HTML, we must detect and replace the elements that represent a content item – this can be done with the replace option of parseHTML.
Aha! Now we’re returning our own React component instead of the original paragraph element. The LinkedItem component is then responsible for determining which component should be rendered for the content item.
Finally, we also can replace both inline assets and links to other content items. We can add support for this in a similar way as the content items, we need to replace elements with React components.
The InlineAsset component converts to a Picture element for responsive images.
Whereas the InlineLink component converts to a Gatsby Link component.