Can you use a block filter to add an inline style to a core block?

Question

I want to create a block filter that adds an option to put in a max-width for the block (they select it with the RangeControl component). It can’t just add a class name. It should be an inline style, that adds this to the block: style=”max-width: 50em”.

Is that possible with a block filter? When I use this, it works, but it shows a block validation error in the console.

function addClassFrontEnd(props, block, attributes) {
    if (allowedBlocks.indexOf(block.name) === -1) {
        return props;
    }

    const { className } = props;
    const { hasMaxWidth } = attributes;

    const maxWidth = hasMaxWidth ? hasMaxWidth + "em" : undefined;

    return assign({}, props, {
        className: classnames(
            className,
            hasMaxWidth ? `has-max-width` : ""
        ),
        style: { maxWidth },
    });
}

// Comment out to test the PHP approach defined in intro-to-block-filters.php
addFilter(
    "blocks.getSaveContent.extraProps",
    "mobilebevpros/width-add-front-end-class",
    addClassFrontEnd
);

Is there a better way to handle this? Using a class would be ideal, but I’d have to make a ton of classes: has-maxwidth-50em, has-max-width-51em, etc.

0
Elizabeth 3 weeks 2022-01-07T13:51:49-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse