emersonthis
emersonthis

Reputation: 33408

How to add a setting to the WordPress Gutenberg editor

I'm trying to write a simple plugin that will alter the behavior of the Edit Post screen (now called Gutenberg). I'm using @wordpress/scripts to bundle the javascript. The following code will work to get the control to appear... but when I click the toggle it reloads the page instead of changing the state.

What am I doing wrong? I can't find any documentation on how to use state in the context of the Gutenberg editor.

import { registerPlugin } from '@wordpress/plugins';
import { PluginMoreMenuItem } from '@wordpress/edit-post';
import { pencil } from '@wordpress/icons';
import { ToggleControl } from '@wordpress/components';
import { withState } from '@wordpress/compose';
 
const HemingwayModeToggleControl = withState( {
    hemingwayMode: false,
} )( ( { hemingwayMode, setState } ) => (
    <ToggleControl
        label="Hemingway mode"
        help={ hemingwayMode ? 'Hemingway mode is on.' : 'Hemingway mode is off.' }
        checked={ hemingwayMode }
        onChange={ () => setState( ( state ) => ( { hemingwayMode: ! state.hemingwayMode } ) ) }
    />
) );

const HemingwayModeMoreMenuItem = () => (
    <PluginMoreMenuItem
        icon={pencil}
    >
        <HemingwayModeToggleControl />
    </PluginMoreMenuItem>
);

registerPlugin( 'hemingway-mode-more-menu', { render: HemingwayModeMoreMenuItem } );

Upvotes: 0

Views: 765

Answers (1)

katya_leurdo
katya_leurdo

Reputation: 21

The problem here is that every component in this slot is wrapped with <button></button>. So, when you hit your toggle, you rather hit this button. But in your case I think this is not important, and you can use button onClick event to set your state. Here is updated code and it is working.

import { registerPlugin } from '@wordpress/plugins';
import { PluginMoreMenuItem } from '@wordpress/edit-post';
import { pencil } from '@wordpress/icons';
import { ToggleControl } from '@wordpress/components';
import { withState } from '@wordpress/compose';

const HemingwayModeMoreMenuItem = withState( {hemingwayMode: false} )(
    ({ hemingwayMode, setState }) => (
        <PluginMoreMenuItem
            icon={pencil}
            onClick={ (e) => {
                e.preventDefault();
                setState( ( state ) => ( { hemingwayMode: ! state.hemingwayMode } ) )
            } }
        >

        <ToggleControl
            label="Hemingway mode"
            help={ hemingwayMode ? 'Hemingway mode is on.' : 'Hemingway mode is off.' }
            checked={ hemingwayMode }
        />

        </PluginMoreMenuItem>
    )
);

registerPlugin( 'hemingway-mode-more-menu', { render: HemingwayModeMoreMenuItem } );

The rest problem is, that More Tools & Options section closes when the button is clicked. This behaviour is default and I do not know how to override it.

Upvotes: 2

Related Questions