-
-
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 } />; | |
} | |
} ); |
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.
@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
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.