@wordpress/block-editor Edit

This module allows you to create and use standalone block editors.

Installation

Install the module

npm install @wordpress/block-editor --save

This package assumes that your code will run in an ES2015+ environment. If you’re using an environment that has limited or no support for such language features and APIs, you should include the polyfill shipped in @wordpress/babel-preset-default in your code.

Top ↑

Usage

import {
    BlockEditorProvider,
    BlockList,
    BlockTools,
    WritingFlow,
    ObserveTyping,
} from '@wordpress/block-editor';
import { SlotFillProvider, Popover } from '@wordpress/components';
import { useState } from '@wordpress/element';

function MyEditorComponent() {
    const [ blocks, updateBlocks ] = useState( [] );

    return (
        <BlockEditorProvider
            value={ blocks }
            onInput={ ( blocks ) => updateBlocks( blocks ) }
            onChange={ ( blocks ) => updateBlocks( blocks ) }
        >
            <SlotFillProvider>
                <BlockTools>
                    <WritingFlow>
                        <ObserveTyping>
                            <BlockList />
                        </ObserveTyping>
                    </WritingFlow>
                </BlockTools>
                <Popover.Slot />
            </SlotFillProvider>
        </BlockEditorProvider>
    );
}

// Make sure to load the block editor stylesheets too
// import '@wordpress/components/build-style/style.css';
// import '@wordpress/block-editor/build-style/style.css';

In this example, we’re instantiating a block editor. A block editor is composed by a BlockEditorProvider wrapper component where you pass the current array of blocks and on each change the onInput or onChange callbacks are called depending on whether the change is considered persistent or not.

Inside BlockEditorProvider, you can nest any of the available @wordpress/block-editor UI components to build the UI of your editor.

In the example above we’re rendering the BlockList to show and edit the block list. For instance we could add a custom sidebar and use the BlockInspector component to be able to edit the advanced settings for the currently selected block. (See the API for the list of all the available components).

The BlockTools component is used to render the toolbar for a selected block.

In the example above, there’s no registered block type, in order to use the block editor successfully make sure to register some block types. For instance, registering the core block types can be done like so:

import { registerCoreBlocks } from '@wordpress/block-library';

registerCoreBlocks();

// Make sure to load the block stylesheets too
// import '@wordpress/block-library/build-style/style.css';
// import '@wordpress/block-library/build-style/editor.css';
// import '@wordpress/block-library/build-style/theme.css';

Top ↑

API

Top ↑

AlignmentControl

Related

Top ↑

AlignmentToolbar

Related

Top ↑

Autocomplete

Related

Top ↑

BlockAlignmentControl

Related

Top ↑

BlockAlignmentToolbar

Related

Top ↑

BlockBreadcrumb

Block breadcrumb component, displaying the hierarchy of the current block selection as a breadcrumb.

Parameters

  • props Object: Component props.
  • props.rootLabelText string: Translated label for the root element of the breadcrumb trail.

Returns

  • WPElement: Block Breadcrumb.

Top ↑

BlockColorsStyleSelector

Undocumented declaration.

Top ↑

BlockContextProvider

Component which merges passed value with current consumed block context.

Related

Parameters

  • props BlockContextProviderProps:

Top ↑

BlockControls

Undocumented declaration.

Top ↑

BlockEdit

Undocumented declaration.

Top ↑

BlockEditorKeyboardShortcuts

Undocumented declaration.

Top ↑

BlockEditorProvider

Undocumented declaration.

Top ↑

BlockFormatControls

Undocumented declaration.

Top ↑

BlockIcon

Related

Top ↑

BlockInspector

Related

Top ↑

BlockList

Undocumented declaration.

Top ↑

BlockMover

Related

Top ↑

BlockNavigationDropdown

Undocumented declaration.

Top ↑

BlockPreview

BlockPreview renders a preview of a block or array of blocks.

Related

Parameters

  • preview Object: options for how the preview should be shown
  • preview.blocks Array|Object: A block instance (object) or an array of blocks to be previewed.
  • preview.viewportWidth number: Width of the preview container in pixels. Controls at what size the blocks will be rendered inside the preview. Default: 700.

Returns

  • WPComponent: The component to be rendered.

Top ↑

BlockSelectionClearer

Undocumented declaration.

Top ↑

BlockSettingsMenu

Undocumented declaration.

Top ↑

BlockSettingsMenuControls

Related

Parameters

  • props Object: Fill props.

Returns

  • WPElement: Element.

Top ↑

BlockStyles

Undocumented declaration.

Top ↑

BlockTitle

Renders the block’s configured title as a string, or empty if the title
cannot be determined.

Usage

<BlockTitle
    clientId="afd1cb17-2c08-4e7a-91be-007ba7ddc3a1"
    maximumLength={ 17 }
/>

Parameters

  • props Object:
  • props.clientId string: Client ID of block.
  • props.maximumLength number|undefined: The maximum length that the block title string may be before truncated.
  • props.context string|undefined: The context to pass to getBlockLabel.

Returns

  • JSX.Element: Block title.

Top ↑

BlockToolbar

Related

Top ↑

BlockTools

Renders block tools (the block toolbar, select/navigation mode toolbar, the
insertion point and a slot for the inline rich text toolbar). Must be wrapped
around the block content and editor styles wrapper or iframe.

Parameters

  • $0 Object: Props.
  • $0.children Object: The block content and style container.
  • $0.__unstableContentRef Object: Ref holding the content scroll container.

Top ↑

BlockVerticalAlignmentControl

Related

Top ↑

BlockVerticalAlignmentToolbar

Related

Top ↑

ButtonBlockAppender

Related

Top ↑

ButtonBlockerAppender

Deprecated

Use ButtonBlockAppender instead.

Top ↑

ColorPalette

Undocumented declaration.

Top ↑

ColorPaletteControl

Undocumented declaration.

Top ↑

ContrastChecker

Related

Top ↑

CopyHandler

Related

Top ↑

createCustomColorsHOC

A higher-order component factory for creating a ‘withCustomColors’ HOC, which handles color logic
for class generation color value, retrieval and color attribute setting.

Use this higher-order component to work with a custom set of colors.

Usage

const CUSTOM_COLORS = [
    { name: 'Red', slug: 'red', color: '#ff0000' },
    { name: 'Blue', slug: 'blue', color: '#0000ff' },
];
const withCustomColors = createCustomColorsHOC( CUSTOM_COLORS );
// ...
export default compose(
    withCustomColors( 'backgroundColor', 'borderColor' ),
    MyColorfulComponent
);

Parameters

  • colorsArray Array: The array of color objects (name, slug, color, etc… ).

Returns

  • Function: Higher-order component.

Top ↑

DefaultBlockAppender

Undocumented declaration.

Top ↑

FontSizePicker

Related

Top ↑

getColorClassName

Returns a class based on the context a color is being used and its slug.

Parameters

  • colorContextName string: Context/place where color is being used e.g: background, text etc…
  • colorSlug string: Slug of the color.

Returns

  • ?string: String with the class corresponding to the color in the provided context. Returns undefined if either colorContextName or colorSlug are not provided.

Top ↑

getColorObjectByAttributeValues

Provided an array of color objects as set by the theme or by the editor defaults,
and the values of the defined color or custom color returns a color object describing the color.

Parameters

  • colors Array: Array of color objects as set by the theme or by the editor defaults.
  • definedColor ?string: A string containing the color slug.
  • customColor ?string: A string containing the customColor value.

Returns

  • ?Object: If definedColor is passed and the name is found in colors, the color object exactly as set by the theme or editor defaults is returned. Otherwise, an object that just sets the color is defined.

Top ↑

getColorObjectByColorValue

Provided an array of color objects as set by the theme or by the editor defaults, and a color value returns the color object matching that value or undefined.

Parameters

  • colors Array: Array of color objects as set by the theme or by the editor defaults.
  • colorValue ?string: A string containing the color value.

Returns

  • ?Object: Color object included in the colors array whose color property equals colorValue. Returns undefined if no color object matches this requirement.

Top ↑

getFontSize

Returns the font size object based on an array of named font sizes and the namedFontSize and customFontSize values.
If namedFontSize is undefined or not found in fontSizes an object with just the size value based on customFontSize is returned.

Parameters

  • fontSizes Array: Array of font size objects containing at least the “name” and “size” values as properties.
  • fontSizeAttribute ?string: Content of the font size attribute (slug).
  • customFontSizeAttribute ?number: Contents of the custom font size attribute (value).

Returns

  • ?Object: If fontSizeAttribute is set and an equal slug is found in fontSizes it returns the font size object for that slug. Otherwise, an object with just the size value based on customFontSize is returned.

Top ↑

getFontSizeClass

Returns a class based on fontSizeName.

Parameters

  • fontSizeSlug string: Slug of the fontSize.

Returns

  • string: String with the class corresponding to the fontSize passed. The class is generated by appending ‘has-‘ followed by fontSizeSlug in kebabCase and ending with ‘-font-size’.

Top ↑

getFontSizeObjectByValue

Returns the corresponding font size object for a given value.

Parameters

  • fontSizes Array: Array of font size objects.
  • value number: Font size value.

Returns

  • Object: Font size object.

Top ↑

getGradientSlugByValue

Retrieves the gradient slug per slug.

Parameters

  • gradients Array: Gradient Palette
  • value string: Gradient value

Returns

  • string: Gradient slug.

Top ↑

getGradientValueBySlug

Retrieves the gradient value per slug.

Parameters

  • gradients Array: Gradient Palette
  • slug string: Gradient slug

Returns

  • string: Gradient value.

Top ↑

getPxFromCssUnit

Returns the px value of a cssUnit. The memoized version of getPxFromCssUnit;

Parameters

  • cssUnit string:
  • options Object:

Returns

  • string: returns the cssUnit value in a simple px format.

Top ↑

getTypographyClassesAndStyles

Provides the CSS class names and inline styles for a block’s typography support
attributes.

Parameters

  • attributes Object: Block attributes.

Returns

  • Object: Typography block support derived CSS classes & styles.

Top ↑

InnerBlocks

Related

Top ↑

Inserter

Undocumented declaration.

Top ↑

InspectorAdvancedControls

Undocumented declaration.

Top ↑

InspectorControls

Related

Top ↑

JustifyContentControl

Related

Top ↑

JustifyToolbar

Related

Top ↑

LineHeightControl

Related

Top ↑

MediaPlaceholder

Related

Top ↑

MediaReplaceFlow

Related

Top ↑

MediaUpload

Related

Top ↑

MediaUploadCheck

Related

Top ↑

MultiSelectScrollIntoView

Deprecated

Scrolls the multi block selection end into view if not in view already. This
is important to do after selection by keyboard.

Top ↑

Undocumented declaration.

Top ↑

ObserveTyping

Related

Top ↑

PanelColorSettings

Undocumented declaration.

Top ↑

PlainText

Related

Top ↑

RichText

Related

Top ↑

RichTextShortcut

Undocumented declaration.

Top ↑

RichTextToolbarButton

Undocumented declaration.

Top ↑

SETTINGS_DEFAULTS

The default editor settings

Type Definition

  • SETTINGS_DEFAULT Object

Properties

  • alignWide boolean: Enable/Disable Wide/Full Alignments
  • supportsLayout boolean: Enable/disable layouts support in container blocks.
  • imageEditing boolean: Image Editing settings set to false to disable.
  • imageSizes Array: Available image sizes
  • maxWidth number: Max width to constraint resizing
  • allowedBlockTypes boolean|Array: Allowed block types
  • hasFixedToolbar boolean: Whether or not the editor toolbar is fixed
  • focusMode boolean: Whether the focus mode is enabled or not
  • styles Array: Editor Styles
  • keepCaretInsideBlock boolean: Whether caret should move between blocks in edit mode
  • bodyPlaceholder string: Empty post placeholder
  • titlePlaceholder string: Empty title placeholder
  • canLockBlocks boolean: Whether the user can manage Block Lock state
  • codeEditingEnabled boolean: Whether or not the user can switch to the code editor
  • generateAnchors boolean: Enable/Disable auto anchor generation for Heading blocks
  • __experimentalCanUserUseUnfilteredHTML boolean: Whether the user should be able to use unfiltered HTML or the HTML should be filtered e.g., to remove elements considered insecure like iframes.
  • __experimentalBlockDirectory boolean: Whether the user has enabled the Block Directory
  • __experimentalBlockPatterns Array: Array of objects representing the block patterns
  • __experimentalBlockPatternCategories Array: Array of objects representing the block pattern categories
  • __unstableGalleryWithImageBlocks boolean: Whether the user has enabled the refactored gallery block which uses InnerBlocks

Top ↑

SkipToSelectedBlock

Related

Top ↑

store

Store definition for the block editor namespace.

Related

Top ↑

storeConfig

Block editor data store configuration.

Related

Top ↑

ToolSelector

Undocumented declaration.

Top ↑

transformStyles

Applies a series of CSS rule transforms to wrap selectors inside a given class and/or rewrite URLs depending on the parameters passed.

Parameters

  • styles Array: CSS rules.
  • wrapperClassName string: Wrapper Class Name.

Returns

  • Array: converted rules.

Top ↑

Typewriter

Ensures that the text selection keeps the same vertical distance from the
viewport during keyboard events within this component. The vertical distance
can vary. It is the last clicked or scrolled to position.

Top ↑

URLInput

Related

Top ↑

URLInputButton

Related

Top ↑

URLPopover

Related

Top ↑

useBlockDisplayInformation

Hook used to try to find a matching block variation and return
the appropriate information for display reasons. In order to
to try to find a match we need to things:
1. Block’s client id to extract it’s current attributes.
2. A block variation should have set isActive prop to a proper function.

If for any reason a block variaton match cannot be found,
the returned information come from the Block Type.
If no blockType is found with the provided clientId, returns null.

Parameters

  • clientId string: Block’s client id.

Returns

  • ?WPBlockDisplayInformation: Block’s display information, or null when the block or its type not found.

Top ↑

useBlockEditContext

The useBlockEditContext hook provides information about the block this hook is being used in.
It returns an object with the name, isSelected state, and the clientId of the block.
It is useful if you want to create custom hooks that need access to the current blocks clientId
but don’t want to rely on the data getting passed in as a parameter.

Returns

  • Object: Block edit context

Top ↑

useBlockProps

This hook is used to lightly mark an element as a block element. The element
should be the outermost element of a block. Call this hook and pass the
returned props to the element to mark as a block. If you define a ref for the
element, it is important to pass the ref to this hook, which the hook in turn
will pass to the component through the props it returns. Optionally, you can
also pass any other props through this hook, and they will be merged and
returned.

Parameters

  • props Object: Optional. Props to pass to the element. Must contain the ref if one is defined.
  • options Object: Options for internal use only.
  • options.__unstableIsHtml boolean:

Returns

  • Object: Props to pass to the element to mark as a block.

Top ↑

useCachedTruthy

Keeps an up-to-date copy of the passed value and returns it. If value becomes falsy, it will return the last truthy copy.

Parameters

  • value any:

Returns

  • any: value

Top ↑

useInnerBlocksProps

This hook is used to lightly mark an element as an inner blocks wrapper
element. Call this hook and pass the returned props to the element to mark as
an inner blocks wrapper, automatically rendering inner blocks as children. If
you define a ref for the element, it is important to pass the ref to this
hook, which the hook in turn will pass to the component through the props it
returns. Optionally, you can also pass any other props through this hook, and
they will be merged and returned.

Related

Parameters

  • props Object: Optional. Props to pass to the element. Must contain the ref if one is defined.
  • options Object: Optional. Inner blocks options.

Top ↑

useSetting

Hook that retrieves the given setting for the block instance in use.

It looks up the settings first in the block instance hierarchy.
If none is found, it’ll look it up in the block editor store.

Usage

const isEnabled = useSetting( 'typography.dropCap' );

Parameters

  • path string: The path to the setting.

Returns

  • any: Returns the value defined for the setting.

Top ↑

Warning

Related

Top ↑

withColorContext

Undocumented declaration.

Top ↑

withColors

A higher-order component, which handles color logic for class generation color value, retrieval and color attribute setting.

For use with the default editor/theme color palette.

Usage

export default compose(
    withColors( 'backgroundColor', { textColor: 'color' } ),
    MyColorfulComponent
);

Parameters

  • colorTypes ...(Object|string): The arguments can be strings or objects. If the argument is an object, it should contain the color attribute name as key and the color context as value. If the argument is a string the value should be the color attribute name, the color context is computed by applying a kebab case transform to the value. Color context represents the context/place where the color is going to be used. The class name of the color is generated using ‘has’ followed by the color name and ending with the color context all in kebab case e.g: has-green-background-color.

Returns

  • Function: Higher-order component.

Top ↑

withFontSizes

Higher-order component, which handles font size logic for class generation,
font size value retrieval, and font size change handling.

Parameters

  • fontSizeNames ...(Object|string): The arguments should all be strings. Each string contains the font size attribute name e.g: ‘fontSize’.

Returns

  • Function: Higher-order component.

Top ↑

WritingFlow

Handles selection and navigation across blocks. This component should be
wrapped around BlockList.

Parameters

  • props Object: Component properties.
  • props.children WPElement: Children to be rendered.

Top ↑

Contributing to this package

This is an individual package that’s part of the Gutenberg project. The project is organized as a monorepo. It’s made up of multiple self-contained software packages, each with a specific purpose. The packages in this monorepo are published to npm and used by WordPress as well as other software projects.

To find out more about contributing to this package or Gutenberg as a whole, please read the project’s main contributor guide.