What is the proper way to apply styles to children in custom blocks?
-
I created a block that makes it possible to apply an offset backdrop to an image. Then, I wanted to achieve what I expected to be a simple goal
- Allow the user to select a background colour by specifying it in the “support” section of the block.json file
- Define a default background colour
- Apply that colour to the backdrop (which is a child of the element I run “useBlockProps()” on.
I encountered multiple issues, the last of them is, in my view, a bug.
Firstly, a custom colour is handled differently from a preset theme colour. In the case of a preset theme colour, a slug is applied to the class name: “has-red-background”. In the case of a custom colour, a background colour is directly specified using the “style” attribute and a hex colour code.
In the editor, this problem is simply overcome by specifying: “style={useBlockprops().style}” on the child one wants to apply the styles on. Then, an rgb colour code is always used.
However, when doing the same in the save()-method, the block crashes. Apparently, it is not possible to utilise “useBlockProps()” in the save()-method.
I created a workaround like this:
export default function save({ attributes }) { const { backgroundColor } = attributes; const style = useBlockProps.save().style; const colorClass = backgroundColor && !(style?.backgroundColor)?
has-${backgroundColor}-background
: ""; return ( <div {...useBlockProps.save()}> <div class={backdrop ${colorClass}
} style={style}></div> <InnerBlocks.Content /> </div> ) }However, when I do this and specify a custom color, the validation fails when I reload the editor:
Block validation: Block validation failed for
test/overlap-image
({name: 'test/overlap-image', icon: {…}, keywords: Array(0), attributes: {…}, providesContext: {…},?…}). Content generated bysave
function: <div class="wp-block-test-overlap-image overlap-image has-grey-background-color has-background" style="background-color:#5d577f"><div class="backdrop " style="background-color:#5d577f"></div></div> Content retrieved from post body: <div class="wp-block-test-overlap-image overlap-image has-background" style="background-color:#5d577f"><div class="backdrop " style="background-color:#5d577f"></div></div>“grey” is the default colour I specified in the block.json file. It magically appears in validation.
Will I simply have to revert to defining a ColorPicker myself (where the colour is always saved as a valid hex code) or is there some way to avoid this?
Any help or confirmation that this is a bug is greatly appreciated.
The code can be downloaded here:https://drive.google.com/drive/folders/1S9jiYIJDx7unxglNTibsIePcSPtdT3fI?usp=sharing
- The topic ‘What is the proper way to apply styles to children in custom blocks?’ is closed to new replies.