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:
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!
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!