Really quick block development

Nicola Heald

will be doing the talking soon

Really quick block development

JavaScript is awful

Modern JavaScript is nice

Browsers are awful

Webpack? Babel? ESWhat? Transpiling JSX?

Let's not deal with any of that.

Get JavaScript

Make sure you have npm installed

Create a plugin for your block

$ npx create-guten-block my-block

Start the development environment

$ cd my-block
$ npm start

You're ready to go without having to deal with the awfulness!

Blocks have

  • An edit component that provides the editing UI.
  • A save component the generates the HTML to save in the post.
  • Attributes that define the block's data. (Think of attributes like defining what arguments a shortcode has.)

Let's write some code!

That code in full

import './style.scss';
import './editor.scss';

const attributes = {
	quote: {
		type: 'string'
	}
};

function edit( props ) {
	const setQuote = ( changeEvent ) => {
		props.setAttributes( { quote: changeEvent.target.value } );
	};
	return (
		<div>
			<p>Pick your favourite Obi-Wan quote!</p>
			<select onChange={ setQuote }>
				<option></option>
				<option>Hello there!</option>
				<option>They'll be back, and in greater numbers.</option>
				<option>Darth Vader is your dad!</option>
			</select>
		</div>
	);
}

function save( props ) {
	return <p>{ props.attributes.quote }</p>;
}

wp.blocks.registerBlockType( 'cgb/block-my-block', {
	title: wp.i18n.__( 'my-block - CGB Block' ), // Block title.
	icon: 'shield',
	category: 'common',
	edit: edit,
	save: save,
	attributes: attributes,
} );

Resources

You Don't Know JavaScript
https://github.com/getify/You-Dont-Know-JS
Gutenberg Block Examples
https://github.com/WordPress/gutenberg-examples/
Gutenberg Handbook
https://developer.wordpress.org/block-editor/
Getting started with React
https://reactjs.org/docs/getting-started.html

slides available at http://notnownikki.com/talks/