Fields middleware for Gutenberg

At the moment, registering fields for your Gutenberg block requires a bunch of repetitive code to produce similar UI.

For instance, to produce a text control, you need to do something like this:

el( wp.blocks.InspectorControls.TextControl, {
	value: url,
	onChange: function( newVal ) {
		props.setAttributes({
			url: newVal
		});
	},
	placeholder: __( 'Enter a GitHub Gist URL' ),
} );Code language: JavaScript (javascript)

See? A lot of boilerplate that you need to repeat for each text control.

For the simple UI, this boilerplate shouldn't be necessary. I'd much rather define a field type when registering the attribute:

attributes: {
	url: {
		type: 'string',
		field: 'text',
	}
},Code language: CSS (css)

It sure would be awesome if this existed as middleware!

3 Comments

Grzegorz Ziółkowski March 19, 2018 Reply

It’s totally doable and we have a few examples in core like className or anchor. We also investigate simplifications around block’s alignment: https://github.com/WordPress/gutenberg/pull/5099.

Jason Bahl April 20, 2018 Reply

An API like this (if on the server) where you define the attributes and declare the type of field that should be associated with it would empower the Gutenberg interface to interact with the block, but would also empower other clients (Calypso, iOS, Android apps, custom, etc) to access the block registry and have enough info to generate an interface to interact with the blocks.

I know there’s progress being made to head in that direction here: https://github.com/WordPress/gutenberg/pull/5802

Looking forward to more progress in that direction.

I think the more we treat WordPress as the and Gutenberg as just the UI to interact with the blocks, where block definitions (including field declarations, etc) are provided by the WordPress server, then we empower WordPress to be useful in many more contexts than just the WP-Admin.

Leave a Reply