Instantly share code, notes, and snippets.

Embed
What would you like to do?
Basic Gutenberg Block, with a RichText Component and a Button on a Toolbar thats logs to console - https://codeamp.com/interacting-with-gutenbergs-richtext-component-using-a-button/
var el = wp.element.createElement;
const { __ } = wp.i18n; // Import __() from wp.i18n
const { registerBlockType } = wp.blocks; // Import registerBlockType() from wp.blocks
const { RichText, BlockControls, BlockFormatControls, AlignmentToolbar } = wp.editor;
const { Button, Dashicon, Tooltip, IconButton, Toolbar } = wp.components;
const { Component, Fragment } = wp.element;
//standard registerBlockType init
registerBlockType( 'my-block-plugin/block-w-insert-shortcode', {
title: 'Block w Shortcode Button', //any title you like
icon: 'universal-access-alt', //any dashicon or svg
category: 'layout', //which category to appear under
//schema of attributes
attributes: {
content: {
type: 'array',
source: 'children'
}
},
//for adding things like a rich text editor, and controls - the editor
edit: function( props ) {
var content = props.attributes.content;
//udpates the attribute `content` when the editor is updated,
function onChangeContent( newContent ) {
props.setAttributes( { content: newContent } );
}
//called when our custom toolbar button is pressed
function onClickShortcodeButton( event ) {
console.log("clicked insert shortcode button");
}
return [
el( //the toolbar
BlockControls,
{
key: 'controls',
controls: [
{
icon: 'edit',
title: __( 'Insert Shortcode' ),
onClick: onClickShortcodeButton
}
]
}
),
el( //the richtext editor
RichText,
{
key: 'editable',
tagName: 'p',
className: props.className,
onChange: onChangeContent,
value: content,
keepPlaceholderOnFocus: true
}
),
];
},
//for saving to the DB
save: function( props ) {
//save the content variable
var content = props.attributes.content;
return el( RichText.Content, {
className: props.className,
value: content
} );
},
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment