Dirk J. Faber
Dirk J. Faber

Reputation: 4691

Adding inline style to Gutenberg core blocks in the editor

In the Gutenberg editor I am trying to add inline styling to all (including core) blocks in the editor. Using editor.BlockEdit, it is possible to make changes to all the blocks in the editor. For example, if I want to wrap them all and to the wrapper add some inline style (in the case a red color), I can do:

const withColorControl = createHigherOrderComponent((BlockEdit) => {
  return (props) => {
    return (
      <div style={{color: 'red'}}>
        <BlockEdit {...props}/>
      </div>
    );
  };
}, 'withColorControl');

addFilter('editor.BlockEdit', 'example/with-color-control', withColorControl);

My problem is though that this creates an extra div, which I do not want. What I would like is for the actual block to receive the inline styles, like so:

<Fragment>
  <BlockEdit {...props} style={{color: 'red'}}/>
</Fragment>

This does not work, therefore my question: How to add inline styles to Gutenberg blocks in the editor without wrapping the block?

PS Saving inline styles or whatnot is not a problem, this merely has to do with the editor.

PS2 Also editor.BlockListBlock does not work. Although this can be used to add a class to the element, I cannot add inline styles.

Upvotes: 2

Views: 2879

Answers (1)

Dirk J. Faber
Dirk J. Faber

Reputation: 4691

There happens to be a wrapperProps you can pass to the component. Not mentioned in the docs, but something I stumbled upon in this question. So what you can do to pass inline styles to blocks in the editor:

const withInlineStyle = createHigherOrderComponent(
  ( BlockListBlock ) => {
    return ( props ) => {
      return (
        <BlockListBlock
          { ...props }
          wrapperProps={{style: {color: 'red'} }}
        />
      );
    }
  },
  'withInlineStyle'
);

wp.hooks.addFilter(
  'editor.BlockListBlock',
  'my-plugin/with-inline-style',
  withInlineStyle
);

It this example, all blocks with have an inline style of color: red.

Upvotes: 6

Related Questions