• I’m creating a Gutenberg block, and I’ve got inspector controls defined; these are showing up and working. Now, what I’m trying to figure out is how to have an event fire after the block inspector controls are drawn.

    The block controls have a variety of options, and which ones should be displayed depends upon the selections of other controls. I have the refresh working, but I would like a callback to set the initial state of the controls.

    I’ve looked through the documentation for registerBlockType, and only see edit() and save() documented as methods on the block attributes. Are there other events that can be defined? Can anyone point me to documentation on this?

    If I’m thinking about this the wrong way, can someone point me to a better method?

Viewing 1 replies (of 1 total)
  • Hi George

    You’ll likely need to define a React component for your inspector control. This component would have its own local state which its render() method can use to decide what HTML to render into the screen.

    Here’s an example of an inspector control component which displays a counter that the user can increment:

    const { Component } = wp.element;
    class MyInspectorControl extends Component {
    	constructor() {
    		super( ...arguments );
    
    		this.incrementCounter = this.incrementCounter.bind( this );
    
    		this.state = {
    			counter: 0,
    		};
    	}
    
    	incrementCounter() {
    		this.setState( { counter: this.state.counter + 1 } );
    	}
    
    	render() {
    		return (
    			<div>
    				<p>Counter: { this.state.counter }</p>
    				<button onClick={ this.incrementCounter }>Increment counter</button>
    			</div>
    		);
    	}
    }
    

    This example component can be used by including the following in your block’s edit function:

    <wp.editor.InspectorControls>
    	<MyInspectorControl />
    </wp.editor.InspectorControls>
    

    The above code uses JSX syntax which means that your plugin will need a compilation step that transforms the JSX into regular JavaScript. I recommend using create-guten-block to easily set up a Gutenberg block plugin that has such a compilation step.

    I hope that helps. If you are comfortable doing so, I’d encourage you to put the code that you have so far into e.g. a GitHub Gist and share it with me so that I can better help you with what you are specifically trying to do.

    • This reply was modified 7 years, 5 months ago by Robert Anderson.
    • This reply was modified 7 years, 5 months ago by Robert Anderson. Reason: Forgot to import Component and InspectorControls
Viewing 1 replies (of 1 total)

The topic ‘Block Editor Events’ is closed to new replies.