Working with inline styles
Directly in your JSX
Sometimes you'll want to set the style attribute on an HTML element directly.
<div style={{ backgroundColor: 'blue' }} />Which will work,
<div style="background-color: blue;" />You can also pass props into this,
function = ( { backgroundColor } ) => {
return <div style={{ backgroundColor }} />;
}Depending on your exact syntax, you could hit transpiler limitations here.
Add a class using PHP
The base class for component Models (opens in a new tab) includes support for a array $inline_styles property.
When _get_data_object() is called as part of the rendering call for a component, the content
of $inline_styles will be mapped to $data->inlineStyles.
You can use this inlineStyles property in any component.
Unlike classes, which are basically required because of CSS Modules, not
every component's template (JSX index) will use the inlineStyles property.
Similar to classes, the final inlineStyles property is a mapping object.
Using the property
You can set the inline_styles directly on any model,
$model = new Model();
$model->inline_styles = [ 'main' => 'background-color: red;' ];Update the schema to allow specific inlineStyles.
This would allow a inlineStyle.main string.
{
"inlineStyles": {
"default": {},
"type": "object",
"properties": {
"menu": {
"default": "",
"type": "string"
}
}
},
}Which is passed into the template,
function = ( {
inlineStyles: { main: '' }, // This keeps Next.js happy and allows the transpiler to do the fallback logic.
} ) => {
return <div styles={ inlineStyles.main } />;
}Which transpiles to,
<div styles="<?php esc_attr( $inlineStyles->main ?? '' ); ?>" />And finally renders as expected,
<div style="background-color: red" />