How to Retrieve Gutenberg Block Styles When Fetching Posts from Headless WordPress for Use in Next.js?

32 Views Asked by At

I'm currently building a Next.js application that retrieves posts from a headless WordPress backend using the REST API. I've noticed that the content returned for Gutenberg blocks includes HTML comments containing style information, such as colors, typography, and other CSS rules, like so:

<!-- wp:paragraph {"style":{"elements":{"link":{"color":{"text":"var:preset|color|orange"}}},"typography":{"lineHeight":"1.8"}},"backgroundColor":"gray","textColor":"blue","fontSize":"small"} -->
<p class="has-drop-cap has-blue-color has-gray-background-color has-text-color has-background has-link-color has-small-font-size" style="line-height:1.8">Here is some text.</p>
<!-- /wp:paragraph -->

However, when I fetch these posts in my Next.js app and render them, the CSS styles from these comments are not applied. I understand that WordPress applies these styles during rendering, but I'm unsure how to replicate this behaviour in my Next.js application.

I've installed the @wordpress/block-library package and imported its CSS styles into my component as follows:

import "@wordpress/block-library/build-style/common.css";
import "@wordpress/block-library/build-style/style.css";
import "@wordpress/block-library/build-style/theme.css";

While some styles from the block library, such as padding for paragraphs with the class .has-background, are being applied correctly (I can see this when inspecting paragraph):

p.has-background {
    padding: 1.25em 2.375em;
}

I've encountered an issue with text and background colour not rendering as expected. For example, when I attempt to apply a colour or background to text within a paragraph block using Gutenberg, the styles are not applied in my Next.js app.

Can anyone offer insights into why the color and background styles defined within Gutenberg blocks are not rendering properly in my Next.js application, despite importing the block library CSS? Additionally, how can I ensure that these styles are correctly applied to my Gutenberg content in Next.js? Any help or suggestions would be greatly appreciated. Thank you!

0

There are 0 best solutions below