Skip to content

Commit

Permalink
Added ESNext examples to format API tutorial (page 2) (#16803)
Browse files Browse the repository at this point in the history
* Added ESNext examples

* Added missing end tags
  • Loading branch information
bfintal authored and mkaz committed Aug 15, 2019
1 parent 0ca1b7e commit 0f3c147
Showing 1 changed file with 70 additions and 0 deletions.
Expand Up @@ -4,6 +4,8 @@ Now that the format is available, the next step is to surface it to the UI. You

Paste this code in `my-custom-format.js`:

{% codetabs %}
{% ES5 %}
```js
( function( wp ) {
var MyCustomButton = function( props ) {
Expand All @@ -27,6 +29,31 @@ Paste this code in `my-custom-format.js`:
);
} )( window.wp );
```
{% ESNext %}
```js
const { registerFormatType } = wp.richText;
const { RichTextToolbarButton } = wp.blockEditor;

const MyCustomButton = props => {
return <RichTextToolbarButton
icon='editor-code'
title='Sample output'
onClick={ () => {
console.log( 'toggle format' );
} }
/>
};

registerFormatType(
'my-custom-format/sample-output', {
title: 'Sample output',
tagName: 'samp',
className: null,
edit: MyCustomButton,
}
);
```
{% end %}

**Important**: note that this code is using two new utilities (`wp.element.createElement`, and `wp.editor.RichTextToolbarButton`) so don't forget adding the corresponding `wp-element` and `wp-editor` packages to the dependencies array in the PHP file along with the existing `wp-rich-text`.

Expand All @@ -42,6 +69,8 @@ By default, the button is rendered on every rich text toolbar (image captions, b
It is possible to render the button only on blocks of a certain type by using `wp.data.withSelect` together with `wp.compose.ifCondition`.
The following sample code renders the previously shown button only on Paragraph blocks:

{% codetabs %}
{% ES5 %}
```js
( function( wp ) {
var withSelect = wp.data.withSelect;
Expand Down Expand Up @@ -82,6 +111,47 @@ The following sample code renders the previously shown button only on Paragraph
);
} )( window.wp );
```
{% ESNext %}
```js
const { compose, ifCondition } = wp.compose;
const { registerFormatType } = wp.richText;
const { RichTextToolbarButton } = wp.blockEditor;
const { withSelect } = wp.data;

const MyCustomButton = props => {
return <RichTextToolbarButton
icon='editor-code'
title='Sample output'
onClick={ () => {
console.log( 'toggle format' );
} }
/>
};

const ConditionalButton = compose(
withSelect( function( select ) {
return {
selectedBlock: select( 'core/editor' ).getSelectedBlock()
}
} ),
ifCondition( function( props ) {
return (
props.selectedBlock &&
props.selectedBlock.name === 'core/paragraph'
);
} )
)( MyCustomButton );

registerFormatType(
'my-custom-format/sample-output', {
title: 'Sample output',
tagName: 'samp',
className: null,
edit: ConditionalButton,
}
);
```
{% end %}

Don't forget adding `wp-compose` and `wp-data` to the dependencies array in the PHP script.

Expand Down

0 comments on commit 0f3c147

Please sign in to comment.