Skip to content

Instantly share code, notes, and snippets.

@Mamaduka
Last active May 4, 2024 10:43
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mamaduka/2b338e8859bee6b35af2dd6791fe6da7 to your computer and use it in GitHub Desktop.
Save Mamaduka/2b338e8859bee6b35af2dd6791fe6da7 to your computer and use it in GitHub Desktop.
/**
* WordPress dependencies
*/
import { createPortal, useEffect, useState } from '@wordpress/element';
import { registerPlugin } from '@wordpress/plugins';
import { Button } from '@wordpress/components';
function MyToolbarButton() {
// Lazy and one time initializations, also gives us a stable reference.
const [ container ] = useState( () => {
const element = document.createElement('div')
element.classList.add('smiley-container')
return element;
} );
// Add the container to the toolbar on component mount.
useEffect( () => {
const editorToolbar = document.querySelector(
'.edit-post-header__toolbar'
);
editorToolbar?.appendChild( container );
return () => {
editorToolbar?.removeChild( container );
};
}, [] );
return createPortal(
<Button icon="smiley"></Button>,
container
);
}
// Register Block Editor plugin
// https://developer.wordpress.org/block-editor/reference-guides/packages/packages-plugins/
registerPlugin( 'toolbar-portal-example', {
render: MyToolbarButton,
} );
@tomjn
Copy link

tomjn commented Apr 27, 2022

You can avoid the DOM manipulation and handle more edge cases such as the default placeholder block by using filters:

https://gist.github.com/tomjn/8795c59c3df54d99b1a92510169ef20d

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