javascriptreactjswordpresswordpress-gutenberg

WordPress Gutenberg get block styles from useBlockProps


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
}

Solution

  • The selected Block Style name as defined in your styles[{...}] is available in the edit() function as className:

    edit({ attributes, setAttributes, className}) {
        console.log(className);
        ...
    }
    

    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 and order: ... 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 save blockProps in the save() so the selected class is applied, eg:

    edit({ attributes, setAttributes, className }) {
        const blockProps = useBlockProps();
        console.log(className);
    
        return (
            <div {...blockProps}>
                <h2>Hello</h2><img />
            </div>
        );
    },
    save({ attributes }) {
        const blockProps = useBlockProps.save();
        return (<div {...blockProps}><h2>Hello</h2><img /></div>)
    }
    

    The generated class applied to the <div> will be .wp-block-myblock-name .is-style-my-style-1