Nicola Heald
will be doing the talking soon
$ wget https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh $ bash install.sh
This installs nvm, the Node Version Manager which lets you install the latest command line JavaScript engine.
$ nvm install lts/*
$ nvm use lts/*
You will need to do this each time you start your session.
$ npx create-guten-block my-new-plugin
$ cd my-new-plugin
$ npm start
Blocks have
Example: a block that lets me select which programming language I'm using, and publishes how that's making me feel in the post.
Defining the attributes that the block has
const attributes = {
currentFeel: {
type: 'string'
}
};
edit
and save
components.
const HelloWorldComponent = function( props ) {
const { name } = props;
return <p>Hello, { name }!</p>;
}
Using that component.
<HelloWorldComponent name="World" />
Define a new React Component for the editing UI
const edit = function( props ) {
A block's properties have a function for setting attributes. Using it makes sure that the editor is notified that the block has changed and the post is updated.
const { setAttributes } = props;
The attributes
are one of the component's properties.
We get the currentFeel
from the attributes
so we can render a select control with the current feeling selected.
const { currentFeel } = props.attributes;
Define a function we can use to set the new attribute value when the select control changes.
const setFeels = ( event ) => {
setAttributes(
{ currentFeel: event.target.value }
);
};
Render the component as a prompt and a select control.
return (
<p>Today, I am writing
<select
onChange={ setFeels } value={ currentFeel }>
<option></option>
<option value="angry and tired">Perl</option>
<option value="calm and approachable">JavaScript</option>
</select>
</p>
);
The finished edit component
const edit = function( props ) {
const { setAttributes } = props;
const { currentFeel } = props.attributes;
const setFeels = ( event ) => {
setAttributes(
{ currentFeel: event.target.value }
);
};
return (
<p>Today, I am writing <select onChange={ setFeels } value={ currentFeel }>
<option></option>
<option value="like I want to burn everything">C++</option>
<option value="calm and approachable">JavaScript</option>
</select>
</p>
);
}
Define the save component
const save = function( props ) {
const { currentFeel } = props.attributes;
return (
<p>Today, I am feeling { currentFeel }!</p>
);
};
Register the block!
registerBlockType( 'wpmeetup/block-demo', {
title: __( 'Feelings block' ),
icon: 'shield',
category: 'common',
keywords: [
__( 'How do I feel' ),
],
attributes: attributes,
edit: edit,
save: save,
} );
Further reading: You Don't Know JavaScript - free book series taking you from the basics of JavaScript programming to the more complex ES6 syntax and concepts.
Components can be a lot more complex, responding to external events and having internal state.
More to learn: The React "Getting Started" guide.
slides available at http://notnownikki.com/talks/