diff --git a/docs/designers-developers/developers/tutorials/format-api/2-toolbar-button.md b/docs/designers-developers/developers/tutorials/format-api/2-toolbar-button.md index 8aea061c5ef16..c6e72011f1782 100644 --- a/docs/designers-developers/developers/tutorials/format-api/2-toolbar-button.md +++ b/docs/designers-developers/developers/tutorials/format-api/2-toolbar-button.md @@ -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.