The 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:
- A
backgroundColor
object that holds the color name, slug, and hex color value. - A
setBackgroundColor
method.
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
innerEdit
to make things neater. The variable name is up to you. - We expand upon the original edit function by adding the
PanelColorSettings
component to the Inspector and setting its value to the hex value of the selected color (backgroundColor.color
). - When a different color is chosen, we use the
setBackgroundColor
method to update the value of thebackgroundColor
block attribute. - We use the
getColorClassName
function to generate the CSS class and store it in theclassName
property.getColorClassName
takes a color slug string (backgroundColor.slug
).
When we register our block:
- We remember to declare the
backgroundColor
block attribute. - We use
compose()
to wrap theinnerEdit()
function with thewithColors
function 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.