Last active
May 4, 2024 10:43
-
-
Save Mamaduka/2b338e8859bee6b35af2dd6791fe6da7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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, | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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