*Edit - this was flagged for being off topic, which doesn't make any sense to me. This question is all about block development and the answer came down to my misunderstanding of the save component.
Let me preface by saying, I'm a React newbie - so I can't tell if this issue is stemming from my lack of React knowledge or if it's specific to gutenberg blocks and the save function.
The goal here is to create a custom navigation block (with child/inner blocks) that is more robust and customizeable than the core/navigation block.
The issue is this: I've added a hamburger menu icon from https://hamburger-react.netlify.app/ which is working in the editor. However whenever I try adding it in the same way to the save function so that it will render on the frontend, I get an 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.
Heres my code:
import { registerBlockType } from '@wordpress/blocks'
import {
useBlockProps,
InspectorControls,
PanelColorSettings,
useInnerBlocksProps,
} from '@wordpress/block-editor'
import { __ } from '@wordpress/i18n'
import { useState } from '@wordpress/element'
import './main.css'
import { Divide as Hamburger } from 'hamburger-react'
registerBlockType('des-blocks/navigation', {
edit({ attributes, setAttributes }) {
const blockProps = useBlockProps();
const innerBlocksProps = useInnerBlocksProps();
const { bgColor, textColor } = attributes
const [isOpen, setOpen] = useState(false);
return (
<>
<InspectorControls>
<PanelColorSettings
title={__('Colors', 'des-blocks')}
colorSettings={[
{
label: __('Background Color', 'des-blocks'),
value: bgColor,
onChange: newVal => setAttributes({ bgColor: newVal })
},
{
label: __('Text Color', 'des-blocks'),
value: textColor,
onChange: newVal => setAttributes({ textColor: newVal })
}
]}
/>
</InspectorControls>
<div {...blockProps}>
<Hamburger toggled={isOpen} toggle={setOpen} color={textColor} />
<ul
{...innerBlocksProps}
class="nav-menu"
style={{
'background-color': bgColor,
'color': textColor
}}
/>
</div>
</>
);
},
save({ attributes }) {
const { bgColor, textColor } = attributes
const [isOpen, setOpen] = useState(false);
const blockProps = useBlockProps.save();
const innerBlocksProps = useInnerBlocksProps.save({
style: {
'background-color': bgColor,
'color': textColor
}
});
return (
<>
<div {...blockProps}>
<Hamburger toggled={isOpen} toggle={setOpen} color={textColor} />
<ul
{...innerBlocksProps}
class="nav-menu"
style={{
'background-color': bgColor,
'color': textColor
}}
/>
</div>
</>
)
}
})
This is whats causing a problem in the save function.
<Hamburger toggled={isOpen} toggle={setOpen} color={textColor} />