Gutenberg: How to use block attributes with ServerSideRenderer?

Yes, and it works exactly the same as any other block, no fake attributes are necessary. When the JS needs to display the component it will make the AJAX request to fetch the markup and pass the attributes with it.

The important part to note is that a block in the block editor is still JS. We’re just generating some HTML with PHP.

When the post is saved, that HTML comment markup with the attributes is still saved, it’s the block editor that generates that markup, not your PHP or JS block implementation. Because your save function is empty though, it’ll just be the HTML comment with the attributes.

Likewise, your fake attribute can be eliminated by using useSelect() to read the block editor data store, and in turn eliminating the need for an update TOC button.

Additionally, even though your block is a dynamic PHP rendered block, that doesn’t mean that your edit function needs to be server rendered. It can be entirely JS, it can be both JS and server rendered ( there is a server render component ), it could even be a picture of a cat with no relation to what gets saved. The edit function returns the interactive editor UI, and the save function returns what actually gets stored in the database. The block editor then serializes this to a string and wraps it in the appropriate markup or JSON intermediary for whatever purpose is needed.

Leave a Comment