I keep getting this error with React on the frontend
Uncaught TypeError: Cannot read properties of null (reading 'useState')
I'm trying to use this hamburger component (https://hamburger-react.netlify.app/) in my custom navigation block. It works in the editor but not in the frontend unless I remove state altogether. I would like to use state tho as it tracks whether to open or close the menu.
The code looks like this in my edit.js
import { registerBlockType } from '@wordpress/blocks'
import { useBlockProps, useInnerBlocksProps } from '@wordpress/block-editor'
import { Divide as Hamburger } from 'hamburger-react'
import './main.css'
edit() {
const [isOpen, setOpen] = useState(false);
return (
<div {...blockProps} id="nav-block">
<Hamburger toggled={isOpen} toggle={setOpen} />
<ul {...innerBlocksProps} class="nav-menu" />
</div>
);
},
And my save component looks like this with no dynamic code (learned my lesson about that already).
save() {
const blockProps = useBlockProps.save();
const innerBlocksProps = useInnerBlocksProps.save({});
return(
<div {...blockProps} id="nav-block">
<ul {...innerBlocksProps} class="nav-menu" />
</div>
);
},
I've added a frontend JS file via "viewScript": "file:./view.js"
to my block.json - it works, I've tested it.
And this code is in my view.js file.
import { render, useState } from '@wordpress/element'
import { Divide as Hamburger } from 'hamburger-react'
import './main.css'
window.addEventListener( 'DOMContentLoaded', ( event ) => {
const wrapper = document.getElementById( `nav-block` );
const [isOpen, setOpen] = useState(false);
render( <Hamburger toggled={isOpen} toggle={setOpen} />, wrapper );
} );
Notice that I added useState to the import statement here, while I didn't do so in the edit.js file. This changes nothing, I still get the same error which tells me Wordpress already loads useState - correct me if I'm wrong.
What am I missing here? It seems unique to Wordpress as I've tried researching React useState and it looks like I'm doing everything right.
npm install @wordpress/scripts --save-dev
and usenpm run start
while in development.useState
is not defined in your edit function, so - "I added useState to the import statement here, while I didn't do so in the edit.js file" - why? Even if that wasn't the problem, that variable should still be defined there.