I am adding styles when registering my block:
styles: [
{ name: "my-style-1", label: "Style Name" }
{ name: "my-style-2", label: "Style Name 2" }
],
In the edit() and save() function how can I see which style/classname was selected?
I tried for example:
edit( { attributes, setAttributes, styles } ) {
const blockProps = useBlockProps();
const { quote, name, title } = attributes;
console.log(styles);
console.log(blockProps.styles);
...
But it returns undefined.
I need to use the styles for conditions for example…
if (style == 'my-style-1') {
// do something if style 1 was selected
}
2
Answers
I would recommend you to use Block Variations instead of Block Styles. When creating a variation you can assign attribute values.
For example:
index.php
With scope: ‘transform’ you can select your variation in the block settings on the right side. Once a variation is selected you can access it in your edit and save file like any other attribute.
The selected Block Style name as defined in your styles[{…}] is available in the
edit()
function asclassName
:I’d suggest if you want to reorder elements based on their style, create Block Styles and use CSS flexbox to manage the reordering, eg
display:flex
for your wrapper div andorder: ...
for the child elements (like<img>
and<p>
). By using styles, when the content is saved the underlying HTML markup doesn’t change so less change of getting the dreaded ‘block validation’ error (plus you get a preview of the style in the Editor). Make sure to saveblockProps
in thesave()
so the selected class is applied, eg:The generated class applied to the
<div>
will be.wp-block-myblock-name .is-style-my-style-1