Gutenberg custom block how to send data from plugin index file to js file

1.9k Views Asked by At

I have registered custom block in plugin main/index php file.

register_block_type('gutenberg-custom/show-information', array(
        'editor_script' => 'gutenberg-show-information',
        'style' => 'gutenberg-customblock-css',
    ));

I want to send some data from this PHP file to the js file which contains the actual implementation of the block. The reason is, I need to do an API call from PHP and use that response in the selectbox option in the js code. please see commented code below. Here is the code for js.

edit: function(props) {
      console.log("props", props);
      return el(
        Fragment,
        {},
        el(
          InspectorControls,
          {},
          el(
            PanelBody,
            { title: "Show Settings", initialOpen: true },
            el(
              PanelRow,
              {},
              el(SelectControl, {
                label: "Select Exhibitor",
                options: [    // **these options are static I have given but I want these to be dynamic coming from the plugin main file or can be any PHP file 
                  { label: "Big", value: "100%" },
                  { label: "Medium", value: "50%" },
                  { label: "Small", value: "25%" }
                ],
                onChange: value => {
                  props.setAttributes({ exhibitor_id: value });
                },
                value: props.attributes.exhibitor_id
              })
            )
          )
        ),
        el(
          "div",
          {},
          "[show-information]"
        )
      );
    },
1

There are 1 best solutions below

0
On

when you enqueue your editor script you can "inject" variables passed to the JS:

wp_register_script('gutenberg-show-information', $pathToScript, [], null, true);
wp_localize_script(
  'gutenberg-show-information',
  YOURJSOBJECT,
  ['myVar' => 'foobarbaz'] <--- array of data you want to pass
);
wp_enqueue_script('gutenberg-show-information');

in your javaScript file you can then access YOURJSOBJECT.myVar which should output foobarbaz