Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block editor giving invalid hook call error

I am trying to get the wordpress block editor to load in a react project: https://www.npmjs.com/package/@wordpress/block-editor.

I have set it up exactly as per the example on the npm page but it gives an invalid hook error. I think perhaps it is due to a version mismatch as error suggest?

This is the code:

import {
  BlockEditorProvider,
  BlockList,
  WritingFlow,
  ObserveTyping
} from "@wordpress/block-editor";
import { SlotFillProvider, Popover } from "@wordpress/components";
import { useState } from "@wordpress/element";
import "@wordpress/components/build-style/style.css";
import "@wordpress/block-editor/build-style/style.css";

export default function MyEditorComponent() {
  const [blocks, updateBlocks] = useState([]);

  return (
    <BlockEditorProvider
      value={blocks}
      onInput={(blocks) => updateBlocks(blocks)}
      onChange={(blocks) => updateBlocks(blocks)}
    >
      <SlotFillProvider>
        <Popover.Slot name="block-toolbar" />
        <WritingFlow>
          <ObserveTyping>
            <BlockList />
          </ObserveTyping>
        </WritingFlow>
        <Popover.Slot />
      </SlotFillProvider>
    </BlockEditorProvider>
  );
}

And the typical hook error:

Error
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
See [link] for tips about how to debug and fix this problem.

I have setup a codepen to tyr it here: https://codesandbox.io/s/sleepy-proskuriakova-op59q

I looked up wordpress version of react and it seems to be 16.6.3 so set that in sandbox and used an older version of react scripts (2.1.8) that at the time was using 16.6.2 but no change in error. I tried several combinations of versions with no change.

What is actually causing this error? How can I get this component to load?

like image 298
Guerrilla Avatar asked Jan 21 '21 14:01

Guerrilla


1 Answers

Here is a working codesandbox.

Things I've changed:

  1. react and react-dom to 16.13.1 which is the version used in @wordpress/element
  2. Had to add DropZoneProvider
  3. Install @wordpress/block-library and call registerCoreBlocks

For more code examples you can check the official storybook docs, the source code is in the bottom panel, under the Story tab.

like image 169
Mohamed Ramrami Avatar answered Oct 21 '22 09:10

Mohamed Ramrami