'How to receive className with ServerSideRender of Gutenberg?

I'm trying to render a block from PHP with ServerSideRender as follows:

js file:

/**
 * WordPress dependencies
 */
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
const { ServerSideRender } = wp.components;

/**
 * Internal dependencies
 */
import icons from './../../utils/icons';

registerBlockType( 'name/blockname', {
  title: __( 'blockname' ),
  description: __( 'Lorem Ipsum is simply dummy text of the printing and typesetting industry.' ),
  keywords: [ __( 'recent post' ) ],
  icon: icons.block,
  category: 'xyz',

  edit: ( props ) => {
    const {
      className,
      attributes,
    } = props;

    return (
      <ServerSideRender
        block="name/blockname"
        attributes={ attributes }
        className={ className }
      />
    );
  },

  save: () => {
    return null;
  },
} );

php file:


register_block_type( '.../blockname', array(
   'attributes'      => array(
      'className'    => array(
         'type'      => 'string',
      ),
   ),
   'render_callback' => 'render_block',
) );

function render_block( $attr, $content ) {
    return 'txt';
}

Render:

   <div>txt</div>

Expected:

   <div class="wp-block-name-blockname">txt</div>

Everything seems to work correctly but the div with the class name is not being rendered.

Any suggestion to fix this? thank you in advance.



Solution 1:[1]

You want to change your render_block function to:

function render_block( $attr, $content ) {
  return sprintf(
    '<div class="wp-block-name-blockname %1$s">txt</div>',
    esc_attr( $attr['className'] )
  );
}

Also see the official tutorial of creating dynamic blocks.

Solution 2:[2]

Getting default attributes from the argument passed to render_callback is not supported. There is an open issue here: https://github.com/WordPress/gutenberg/issues/13811. You have to programmatically set className per the example. Included below:

function block_classes( $name, $attributes = array() ) {
    $classes = array( 'wp-block-' . $name );
    if ( isset( $attributes['align'] ) && $attributes['align'] ) {
        array_push( $classes, 'align' . $attributes['align'] );
    }
    if ( isset( $attributes['className'] ) && $attributes['className'] ) {
        array_push( $classes, $attributes['className'] );
    }
    return implode(  ' ', $classes );
}

Solution 3:[3]

This can be done with the get_block_wrapper_attributes() function.

This function returns a string of HTML attributes.

<div <?php echo get_block_wrapper_attributes(); ?>>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Tahi Reu