bitwize
bitwize

Reputation: 63

React component into Wordpress Gutenberg Block Plugin generates 321 React Error

I'm trying to create my own React Component as an external library ( actually I'm using create-react-library for fast scaffolding ) that I want to import and use inside my custom WordPress Gutenberg Block Plugin, for front-end purposes ( I want to render it into the save() function ).

I'm facing with an issue generated by a minified version of react-dom (used by Wordpress Gutenberg I assume ) that tells me that there are some mismatches; here is the explanation of the raised error https://reactjs.org/docs/error-decoder.html/?invariant=321 .

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app

My component uses Reack Hooks, and the error rises when a useState() function is triggered.

So far I am sure that is not a problem related to wrong usages of react hooks, but I think that is related to the fact that my component, which loads and uses other external components, tries to render sub-components with a different react-dom library than the one used by WP Gutenberg.

My newly created custom component works perfectly outside WP Gutenberg environment, so the problem is about how to make these two actors working together.

I use wp-scripts build to create the bundle used by WP hooks for importing, and the relevant message I think is useful to share is

...
[@wordpress/blocks] external {"this":["wp","blocks"]} 42 bytes {index} [built]
[@wordpress/element] external {"this":["wp","element"]} 42 bytes {index} [built]
[@wordpress/i18n] external {"this":["wp","i18n"]} 42 bytes {index} [built]
[react] external {"this":"React"} 42 bytes {index} [built] <- **using external react**

So what can I do to make my React component work without problems with WP Gutenberg Block

Please feel free to ask for more information and details, I will update the post as needed

Upvotes: 1

Views: 1844

Answers (1)

bitwize
bitwize

Reputation: 63

The problem was related to the fact that imported libraries without react and react-dom as peerDependencies have been bundled by webpack during build time in my component. So different version of react and react-dom were living in the same context at the same moment when used by WP plugin, causing the error reported above.

The solution was to delcare in webpack config the external entry, pointing the right dependencies created runtime by WP plugin, and set up in my component react and react-dom as peer dependencies for the project.

Hope this helps.

Upvotes: 1

Related Questions