TL;DR
How can I change the edit
and save
result of a core block without having to re-implement most of its functionality in my own code?
Question
I'm familiar with the block filters and am already able to use them to add attributes or new InspectorControls. However, it bugs me that it seems I cannot update the JSX/HTML of the edit/save without having to overwrite the whole block.
Imagine the following scenario: I want to add a setting to the core/button
block to append an icon after the text. So the final HTML should not be
<div class="wp-block-button">
<a class="wp-block-button__link">Hello World</a>
</div>
but instead the desired result is
<div class="wp-block-button">
<a class="wp-block-button__link">Hello World</a>
<span class="wp-block-button__icon">X</span>
</div>
For save
I could probably use wp.element.cloneElement
to add my own element as an additional child.
But what for edit
? My current understanding is that as long as the block does not use SlotFills, I don't really have an option.
In the usual setup like this
const withInspectorControls = createHigherOrderComponent((BlockEdit) => {
return (props) => {
const { name, attributes, setAttributes } = props
if (name !== 'core/button') {
return <BlockEdit {...props} />
}
const { showIcon } = attributes
return (
<Fragment>
<BlockEdit {...props} />
<InspectorControls>
<PanelBody title={__('Show Icon?', 'my-plugin')}>
<ToggleControl
label={__('Show Icon?', 'my-plugin')}
checked={showIcon}
onChange={(showIcon) => setAttributes({ showIcon })}
/>
</PanelBody>
</InspectorControls>
</Fragment>
)
}
})
addFilter('editor.BlockEdit', 'my-plugin/add-icon-inspector', withInspectorControls)
I could drop the <BlockEdit {..props} />
part and re-implement the button. But looking at the source of the edit I know that I'd have to either re-implement the complete ButtonEdit
method, which I would like to avoid.
Various guides as well as other answers on this stack imply that it makes more sense to create a new block (and de-register/blacklist the core one), is this still valid for 2021?
cloneElement
gives me enough freedoms for save).