-
-
Save aduth/fb1cc9a2296110a62b96383e4b2e8a7c to your computer and use it in GitHub Desktop.
Random Image Block - ES2015+, JSX
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } />; | |
} | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@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 (andwp.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/