withColors Higher Order Component provides our basic Footnote block with the means to add background colors from the default editor or registered theme color palette.
When we wrap a function with the
withColors Higher Order Component, the original function is provided with:
backgroundColorobject that holds the color name, slug, and hex color value.
We set this up by passing the string
backgroundColor to the
withColors function when we “compose” or layer the two functions together. This signifies that we intend to use “backgroundColor” as the name of the block attribute that will store the selected color (as its slug). It also implies that the resulting CSS class for displaying the background color will contain the string “background-color” (as in “.has-colorname-background-color”).
In this example:
- Our new Footnote block will use additional core components, like
PanelColorSettings(which allows us to select and display the background color in the Inspector), and a utility function,
getColorClassName, for generating the name of the CSS background color class.
- We take the edit function from our basic Footnote example and assign it to the variable
innerEditto make things neater. The variable name is up to you.
- We expand upon the original edit function by adding the
PanelColorSettingscomponent to the Inspector and setting its value to the hex value of the selected color (
- When a different color is chosen, we use the
setBackgroundColormethod to update the value of the
- We use the
getColorClassNamefunction to generate the CSS class and store it in the
getColorClassNametakes a color slug string (
When we register our block:
- We remember to declare the
- We use
compose()to wrap the
innerEdit()function with the
withColorsfunction and assign the result as the edit function for the block.
Notice that the save function also uses
getColorClassName to generate the CSS class. Here we get the color slug from the
backgroundColor attribute, unlike in the case of the edit function, where we used
backgroundColor.slug. For the edit function, it was better to use the value coming directly from the
PanelColorSettings component instead of assuming that the block attribute would be updated in time for us to use it.