Dynamic Editor Plugin Icons!

Here’s a fun thing you can do to make your editor plugin icons a little more dynamic. If you monitor the visibility status of your plugin sidebar then you can specify a different icon depending on when it’s currently open or closed.

Register your editor plugin in the usual way with registerPlugin function, and then use the PluginSidebar slot to render your editor plugin UI in a plugin sidebar panel.

Normally, the plugin icon is static but with a call to getActiveGeneralSidebarName via the useSelect hook we can listen for changes to the current active sidebar name. If this matches a string comprised of our custom editor plugin and sidebar name (my-sidebar), then we can use this to conditionally display a closed/open eye icon.

By default the sidebar is not active, so we display the closed eye icon.

And whenever our sidebar is visible we display a different (open eye) icon.

Here’s the full editor plugin code.

import { registerPlugin } from '@wordpress/plugins';
import { PluginSidebar } from '@wordpress/edit-post';
import { __ } from '@wordpress/i18n';
import { Button, PanelBody } from '@wordpress/components';
import { seen, unseen } from '@wordpress/icons';
import { useSelect } from '@wordpress/data';

const MyPlugin = () => {
	const sidebar = useSelect(( select ) => select( 'core/edit-post' ).getActiveGeneralSidebarName(),
 []);

	return (
		<PluginSidebar
			title={ __( 'My Plugin Sidebar' ) }
			name="my-sidebar"
			icon={ sidebar === 'myplugin/my-sidebar' ? seen : unseen }
		>
			<PanelBody>
				<h2>I can see clearly now the rain has gone...</h2>
				<Button variant="secondary">Click Me</Button>
			</PanelBody>
		</PluginSidebar>
	);
};

registerPlugin( 'myplugin', { render: MyPlugin } );

Note, that by using the useSelect hook we effectively subscribe to changes to the current active sidebar. This makes it super-easy to update our editor plugin icon depending on the sidebar visibility.