Round two!
Once I made a simple, sample spoiler box, it was time to jump into the next stage. Customizable, editable, not simple, sample spoiler boxes!
Here’s the best part. All I had to change was the index.js
file from the previous example.
The Javascript
( function( blocks, i18n, element ) { var el = element.createElement; var __ = i18n.__; var RichText = blocks.RichText; blocks.registerBlockType( 'library/spoilers', { title: __( 'Spoiler Warning' ), icon: 'vault', category: 'widgets', supportHTML: false, attributes: { content: { type: 'array', source: 'children', selector: 'div', }, }, edit: function( props ) { var content = props.attributes.content || 'Warning: This post contains spoilers!'; var focus = props.focus; function onChangeContent( newContent ) { props.setAttributes( { content: newContent } ); } return el( RichText, { tagName: 'div', className: props.className, onChange: onChangeContent, value: content, focus: focus, onFocus: props.setFocus } ); }, save: function( props ) { return el( 'div', { className: 'alert alert-danger'}, props.attributes.content ); } } ); } )( window.wp.blocks, window.wp.i18n, window.wp.element );
What’s Different?
A few things. A lot of things. The idea is that we need to pass the content attribute (i.e. our warning) to be processed. This is very much like how you pass attributes through shortcodes, so don’t panic.
var content = props.attributes.content || 'Warning: This post contains spoilers!'; var focus = props.focus; function onChangeContent( newContent ) { props.setAttributes( { content: newContent } ); }
This says “Set the content to ‘Warning: This post contains spoilers!’ if there’s nothing there. Then watch the focus. If the focus changes, use the new content to replace the original content.”
Down in our return el
section, we’ve changed it to be Rich Text (so people can use bold and so on… even though it’s always bold), and the value: content,
is the variable content we edited above.
What’s It Like?
It’s just like any other Block. It inserts itself when you click the icon, it loads the default, and you can edit it:
And that is a simple, editable, Gutenberg Block