'Invalid Hook Call. Using ReactJS in the admin section of WordPress (specifically editing a custom post type)
I want to create a React based custom post type editor in WordPress. I've created a plugin that:
- Registers a custom post type
my-custom-post - Injects
<div id="root"></div>into/wp-admin/post-new.php?post_type=my-custom-post - Builds a simple React app that renders a component in
<div id="root"></div>
/wp-admin/plugins/my-custom-plugin/src/index.js
const {
useState
} = wp.element;
function Example(props) {
const [value, setValue] = useState(new Date());
return <h1>Hello!</h1>;
}
render(
<Example />,
document.getElementById( 'root' )
);
Dependencies
λ yarn list --pattern react
yarn list v1.22.15
├─ @babel/[email protected]
├─ @babel/[email protected]
├─ @babel/[email protected]
├─ @babel/[email protected]
├─ @babel/[email protected]
├─ @babel/[email protected]
├─ @pmmmwh/[email protected]
├─ @svgr/[email protected]
├─ @types/[email protected]
├─ @types/[email protected]
├─ @wojtekmaj/[email protected]
├─ [email protected]
│ └─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
│ └─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
├─ [email protected]
└─ [email protected]
wp-content/plugins/my-custom-plugin/package.json
{
"name": "my-custom-plugin",
"version": "1.0.0",
"description": "I build, therefore I'm awesome.",
"scripts": {
"build": "wp-scripts build",
"format": "wp-scripts format",
"lint:css": "wp-scripts lint-style",
"lint:js": "wp-scripts lint-js",
"start": "wp-scripts start",
"packages-update": "wp-scripts packages-update"
},
"engines": {
"node": ">=8.0.0",
"npm": ">=6.0.0"
},
"devDependencies": {
"@wordpress/scripts": "^20.0.2"
},
"dependencies": {
"react-multi-date-picker": "^3.3.0"
}
}
The Error
react-dom.min.js?ver=17.0.1:141 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 https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
