I have simple block with server-side rendering on frontend.
PHP:
register_block_type( 'some/block', array(
'render_callback' => 'render_my_block',
'attributes' => array(
'stuff' => array(
)
)
));
function render_my_block( $attributes ) {
// $attributes['stuff']
return '<h1>Hello frontend</h1>';
}
Which works, but I also need to render it as a preview in admin area, so I add JS:
registerBlockType( 'some/block', {
title: 'Some block',
attributes: {
stuff : {
}
},
edit( { className, attributes, setAttributes } ) {
return (
<Fragment>
<SomeInput />
<SomeOtherInput />
<Preview>
// I need to get contents of PHP function render_my_block here,
// based on current attributes.stuff
</Preview>
</Fragment>
);
},
save( { attributes } ) {
return null; // server side
}
} );
My question is – what is the correct way to fetch this data? Should I just use wp_ajax_
callback/filter? Or Gutenberg has some better way to handle this?
I already checked how default “Latest Posts” block works – it uses Rest API to get post IDs and titles and then renders them via react. But for my case I just need to return simple HTML string.