Site icon WebDevStudios

Quick Tip: Gutenberg Blocks as JSON

Big Ugly Blobs

When WordPress saves Gutenberg blocks to the database, it smashes them together as a string of markup. When you query that via the REST-API or WPGraphQL? You get this big ugly blob of HTML:

The screenshot above isn’t that bad, but what happens when you have a 2,000 word blog post with images, block quotes and Twitter embeds? When working on a headless frontend, how are you going to create a layout to match your client’s design, when you’re stuck with a big string of HTML?

Maybe reach for regular expressions to pluck out the data? Try using CSS to drill down and style HTML tags? You could totally YOLO that blob of HTML right into a component with dangerouslySetInnerHTML

…but the reality is, losing control over the decision making process for handling data makes for a poor developer experience.

There’s already a standard way to work with APIs that have structured data. To quote the MDN:

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa).

After reading that definition, you might be asking, “If JSON is a standard way to transmit structured data, why isn’t WordPress doing this with Gutenberg blocks?”

That’s the million dollar question.

WPGraphQL Gutenberg to the Rescue

You’re in luck because the WPGraphQL Gutenberg plugin from Peter Pristas converts Gutenberg blocks to JSON!

Using WPGraphQL, you can query for blocksJSON on a page or post and receive a big ugly blob of JSON instead!

Thanks to both the JSON.parse() and .map() methods, you can convert the JSON response from WPGraphQL into an array of objects, and then .map() over it (kind of like the WordPress Loop). This is standard practice when working with JSON in JavaScript.

The following code snippet parses the JSON response, starts a loop, plucks out the ‘core/paragraph’ block, then passes in the data as props:

Thanks to the structure JSON provides, you now have full control over content coming from Gutenberg. Now that’s a good developer experience!

Exit mobile version