Skip to content

Commit

Permalink
Add: Block specific toolbar button sample to the format api tutorial (#…
Browse files Browse the repository at this point in the history
…14113)

## Description
This PR updates the format API tutorial (toolbar button section) to include a sample of a button that only renders on a certain block.
Answers a question posted on #14104.
Closes: #14104

## How has this been tested?
I pasted the sample code on the browser console and verified it works as expected.
  • Loading branch information
jorgefilipecosta authored Feb 27, 2019
1 parent 1010f0d commit 1ed9995
Showing 1 changed file with 51 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,54 @@ Let's check that everything is working as expected. Reload the post/page and sel
![Toolbar with custom button](https://raw.githubusercontent.com/WordPress/gutenberg/master/docs/designers-developers/assets/toolbar-with-custom-button.png)

You may also want to check that upon clicking the button the `toggle format` message is shown in your browser's console.

## Show the button only for specific blocks

By default, the button is rendered on every rich text toolbar (image captions, buttons, paragraphs, etc).
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:

```js
( function( wp ) {
var withSelect = wp.data.withSelect;
var ifCondition = wp.compose.ifCondition;
var compose = wp.compose.compose;
var MyCustomButton = function( props ) {
return wp.element.createElement(
wp.editor.RichTextToolbarButton, {
icon: 'editor-code',
title: 'Sample output',
onClick: function() {
console.log( 'toggle format' );
},
}
);
}
var ConditionalButton = compose(
withSelect( function( select ) {
return {
selectedBlock: select( 'core/editor' ).getSelectedBlock()
}
} ),
ifCondition( function( props ) {
return (
props.selectedBlock &&
props.selectedBlock.name === 'core/paragraph'
);
} )
)( MyCustomButton );

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

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

More advanced conditions can be used, e.g., only render the button depending on specific attributes of the block.

0 comments on commit 1ed9995

Please sign in to comment.