Describe the bug
I am trying to add a FormToggle component to the InspectorControls of the gallery block to allow the user to convert the gallery to a slider.
To Reproduce
This is my code:
const { Fragment } = wp.element;
const {
registerBlockType,
} = wp.blocks;
const {
InspectorControls,
} = wp.editor;
const {
PanelBody,
FormToggle,
} = wp.components;
wp.hooks.addFilter(
'editor.BlockEdit',
'slug/modify-block-edit',
modifyBlockEdit
);
wp.hooks.addFilter(
'blocks.registerBlockType',
'slug/modify-register-block-type',
modifyRegisterBlockType
);
function modifyBlockEdit( BlockEdit ) {
return (props) => {
if ('core/gallery' === props.name) {
const { attributes: { isSlider }, setAttributes } = props;
console.log(isSlider);
return (
<Fragment>
<BlockEdit { ...props } />
<InspectorControls>
<PanelBody title={ 'Slider' }>
<FormToggle
label='Als Slider anzeigen'
checked={ isSlider }
onChange={ setAttributes( {isSlider: ! isSlider } ) }
/>
</PanelBody>
</InspectorControls>
</Fragment>
);
}
return (
<Fragment>
<BlockEdit { ...props } />
</Fragment>
);
};
}
function modifyRegisterBlockType( settings, name ) {
if ('core/gallery' === name) {
settings.attributes.isSlider = {
type: 'boolean',
default: false,
};
}
return settings;
}
After editing a post with a gallery block, the console is filled with true false logs, and it ends in the messages Invariant Violation: "Minified React error #185; visit https://reactjs.org/docs/error-decoder.html?invariant=185 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
I am using Gutenberg 3.2.0.
Am I using the filters wrong? Removing the onChange fixes the infinite loop issue, but without it, the component is a little useless of course :)
Thanks in advance!
My bet is that you need to update the following line
- onChange={ setAttributes( {isSlider: ! isSlider } ) }
+ onChange={ () => setAttributes( {isSlider: ! isSlider } ) }
At the moment it is executed every time FormToggle renders, which triggers another re-render and so forth.
Ha, great, that was the solution, thanks a lot @gziolo! :)
At the moment it is executed every time FormToggle renders, which triggers another re-render and so forth.
Ah okay, thanks for the explanation!
My bet is that you need to update the following line
- onChange={ setAttributes( {isSlider: ! isSlider } ) } + onChange={ () => setAttributes( {isSlider: ! isSlider } ) }At the moment it is executed every time
FormTogglerenders, which triggers another re-render and so forth.
I have been hit by this bug a few times now. Thanks a lot! :)
Most helpful comment
My bet is that you need to update the following line
At the moment it is executed every time
FormTogglerenders, which triggers another re-render and so forth.