How to use svg icon in laraberg custom block?
If you just started to use laraberg (wordpress gutenberg plugin Js) with laravel, you might need to create some custom blocks like to highlight code, to add title blocks in the editor etc.
I have too, so I tried various ways to do that but because I was using plain javascript instead of react and build tools. I was stuck on using the svg icon for my gutenberg custom block.
Now, I got the solution and here it is,
Add svg icon in the custom block
function registerPostTitleBlock() { (function (blocks, blockEditor, element, components) { var el = element.createElement; var RichText = blockEditor.RichText; var useBlockProps = blockEditor.useBlockProps; var InspectorControls = blockEditor.InspectorControls; const icon = el("svg", { viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg" }, el("path", { d: "M6.2 5.2v13.4l5.8-4.8 5.8 4.8V5.2z" })); const block = blocks.registerBlockType('sbt-block/post-title', { apiVersion: 2, title: 'Post title', icon: icon, category: 'text', attributes: { content: { type: 'string', selector: 'h1.post-title', source: 'text', } }, supports: { customClassName: false, }, edit: function (props) { var blockProps = useBlockProps(); return [ el( InspectorControls, { key: 'l8' } ), el(RichText, { tagName: 'h1', key: 'lx4', value: props.attributes.content, preserveWhiteSpace: true, __unstablePastePlainText: true, onChange: content => props.setAttributes({ content: content }), placeholder: "Enter title..", }) ] }, save: function (props) { var blockProps = useBlockProps.save(); return el(RichText.Content, Object.assign(blockProps, { tagName: 'h1', className: 'post-title', value: props.attributes.content }), ); }, }) })(Laraberg.wordpress.blocks, Laraberg.wordpress.blockEditor, Laraberg.wordpress.element, Laraberg.wordpress.components); }
I have created the react element to render the svg icon in the JavaScript, that’s it! It works 🙂