0

I create my gutenberg block. I need hook useEffect for my component and include it:

const { useEffect } = wp.element;

My sample component:

function TestComponent(  ) {
  useEffect(() => {
    console.log('from useEffect');
  })
  return (
   <p>from Test</p>
  )
}

I use TestComponent in edit and save. In edit mode his work normally, but in frontend not render. If i remove useEffect from TestComponent his work in frontend too.

Why useEffect not work in frontend?

2

That's not how blocks work in Gutenberg. Your block code runs entirely in the block editor, and returns 2 things:

  • Components to display in the editor UI
  • Components that when rendered produce HTML that gets saved to the database

That second one is the key part here, the final product is just a string of HTML.

So, if you want to use React in the frontend with your block, you have to implement it yourself, the same way you would if you wanted to use React in a shortcodes implementation. The content is just content, Gutenberg doesn't mean that the frontend pulls in pieces of React code, it's still just static HTML the same as before.

That'd mean saving an entry point to the react implementation of the block, along with all the attributes needed to pass in as props, a mini react application to hydrate/create the block, and some code to bootstrap it by searching for those entry points and spinning up the React components with that initial React.render

There are API tools you can use when registering a block to make sure that your blocks frontend JS assets are loaded at the appropriate time, and that would make a good question to ask on the site as a follow up.

TLDR: A blocks JS in the editor, and the frontend have no connection other than the HTML string that gets saved in the database

If you did want to build a React implementation for your block on the frontend, and want to use the wp element library, you'll need to declare that library as a dependency when enqueing the script

1
  • Thank you. I add parameter edit in component and condition if ( edit ) . In front-end i do my action in js after dom loaded. – kostikovmu Mar 12 '20 at 17:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.