0

If I have a Gutenberg block for which I gather a string that the user enters, but I want to use that string within a react app rendered in the frontend, how can I pass that string?

Defining a Gutenberg block

  save: ({ attributes }) => {
    window.thisVariableWillNotBeSeen = attributes
    console.log(window) // here `thisVariableWillNotBeSeen` is seen, in the frontend it is not
    return (
        <div id="test_react"></div>
    )
  },

Then, a script enqueued as such (within a plugin)

add_action('wp_enqueue_scripts', 'react_enqueue');
function react_enqueue()
{
    $asset_file = include(plugin_dir_path(__FILE__) . 'build/test.asset.php');

    wp_enqueue_script(
        'myBlock',
        plugins_url('build/test.js', __FILE__),
        $asset_file['dependencies'],
        $asset_file['version'],
        true
    );
}

And scr/test.js

const { render } = wp.element
import { Test} from './components/test'

render(<Test />, document.getElementById(`test_react`))

Within export const Test, if I see there console.log(window) I cannot see the global variable I have added in the save function of before

How could I do this?

GWorking
  • 4,011
  • 10
  • 49
  • 90

1 Answers1

0

As said here https://stackoverflow.com/a/44663473/826815 it can be done by rendering a script or also a dataset property, and later fetch this data through the window object or through the DOM

  save: ({ attributes }) => {
    return (
      <Fragment>
        <div id="test_react"></div>
        <div id="test_react_data" data-test={JSON.stringify(attributes)}></div>
        <script type="text/javascript">{`var test_react= ${JSON.stringify(attributes)};`}</script>
      </Fragment>
    )
  },
GWorking
  • 4,011
  • 10
  • 49
  • 90