How to add javascript function in the “save()” of gutenberg block?

WordPress is using React only on it’s backend editor not on frontend. Gutenberg work as follows:

  • You create a block and interacts with it. (edit function)
  • While saving gutenberg put your attributes in save function which in end returns just html
  • WordPress uses comments to identify blocks and storing data related to it. You can view these comments if you switch to Code Editor from Visual Editor. Menu on top right can help you with switching.
  • When you save the post then WordPress take all of the output of save functions in blocks, merge them together and save it to database.
  • This simple html is loading on front end therefore none of your code is working.
  • While on other end if WordPress load that same post in Edit then it redo all the steps take html, read comments and give you an interactive layout.

Gutenberg blocks mostly handles the backend behavior as you can suggest from it’s common name which is backend editor. On front end you are still left with the same old logic which is enqueuing scripts separately and handles front end interactions there.

If you don’t like then you can use an extra file like frontend.js with in each of your block and then use webpack to bundle them and php to enqueue them to the wp_enqueue_scripts. This how WordPress works as of now.

I have found some people using this method to use React on front-end but didn’t find anything on it in docs of gutenberg.

  • In save return an custom react element instead of actual html like <CustomElement />
  • Define a component just like react in your scripts which enqueue on
    front-end and while enqueuing add wp-element dependency, as we’ll need react on front and wp-element is a wrapper of React so no need to use any external library.
  • When WordPress load html on frontend then your custom element will be present there and your script that we loaded on above point can then take control of it.