Skip to content

Instantly share code, notes, and snippets.

@aduth

aduth/block.jsx Secret

Last active August 11, 2020 03:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aduth/fb1cc9a2296110a62b96383e4b2e8a7c to your computer and use it in GitHub Desktop.
Save aduth/fb1cc9a2296110a62b96383e4b2e8a7c to your computer and use it in GitHub Desktop.
Random Image Block - ES2015+, JSX
const { registerBlock, query } = wp.blocks;
const { attr } = query;
function RandomImage( { category } ) {
const src = 'http://lorempixel.com/400/200/' + category;
return <img src={ src } alt={ category } />;
}
registerBlock( 'myplugin/random-image', {
attributes: {
category: attr( 'img', 'alt' )
},
edit( { category }, setAttributes ) {
function setCategory( event ) {
const selected = event.target.querySelector( 'option:checked' );
setAttributes( { category: selected.value } );
event.preventDefault();
}
return (
<form onSubmit={ setCategory }>
{ category ? <RandomImage category={ category } /> : null }
<select value={ category } onChange={ setCategory }>
<option value="sports">Sports</option>
<option value="animals">Animals</option>
<option value="nature">Nature</option>
</select>
</form>
);
},
save( { category } ) {
return <RandomImage category={ category } />;
}
} );
@aduth
Copy link
Author

aduth commented Mar 20, 2017

If you've configured a build process such as Webpack with Babel, there are a few conveniences you may be interested in taking advantage of, particularly writing in JSX. This is the same example from Blocks documentation written as ES2015+ and JSX.

@jhackett1
Copy link

is there a minor destructuring error on line 15? i'm getting a setAttributes is not a function error but if i put that part inside the curly brackets, all is well.

@aduth
Copy link
Author

aduth commented Jun 4, 2020

@jhacket11: Yeah, it would appear to need to be destructured as part of the first argument object. This entire example is quite outdated. For example, the attrs function (and wp.blocks.query) was part of very early Gutenberg implementations and no longer exists.

A more up-to-date reference is the Gutenberg Handbook:

https://developer.wordpress.org/block-editor/tutorials/block-tutorial/writing-your-first-block-type/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment