Skip to content

Instantly share code, notes, and snippets.

@aduth aduth/block.jsx Secret
Last active Jan 11, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.