Skip to content

Instantly share code, notes, and snippets.

@rmorse
Last active December 26, 2018 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmorse/1300421889ec7fbb9217899e61ab703d to your computer and use it in GitHub Desktop.
Save rmorse/1300421889ec7fbb9217899e61ab703d to your computer and use it in GitHub Desktop.
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
} );
},
} );
@carlosenambam
Copy link

Why do you use "key: 'editable' "?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment