WordPress Block.js SVG createElement

Basically, when using wp.element.createElement(),

  1. For attribute names having special characters like a hypen/-, the name should be put in single/double quotes: e.g. 'data-name' and not simply data-name.

    createElement( 'svg', {
        'data-name': 'Layer 1' // like this
        data-name: 'Layer 1'   // not this
    } );
    
  2. The same also goes to attribute names like class which is a reserved JavaScript word/identifier.

    createElement( 'text', {
        'class': 'cls-1'   // use quotes
        className: 'cls-1' // or use className
    } );
    
  3. createElement() can accept nested child elements, just as you can see below.. (for an in-depth explanation/guide, please ask/search on sites like Stack Overflow)

    createElement( 'ul', null,
        createElement( 'li', null, 'One' ),
        createElement( 'li', null,
            createElement( 'b', null, 'Two' )
        ),
        createElement( 'li', null, 'Three' )
    );
    /* Output:
    <ul><li>One</li><li><b>Two</b></li><li>Three</li></ul>
    */
    

So with the SVG markup in the question, the following would do it:

var Amazon = function () {
    var svg = createElement("svg", {
        id: "Layer_1",
        // attributes having special characters in the name should be wrapped in quotes
        "data-name": "Layer 1",
        xmlns: "http://www.w3.org/2000/svg",
        viewBox: "0 0 93.79 38.77"
    }, createElement("defs", null, createElement("style", null, ".cls-1{font-size:35.66px;font-family:MyriadPro-Regular, Myriad Pro;} .cls-2{letter-spacing:-0.01em;} .cls-3{fill:#d39e09;}")), createElement("title", null, "Amazon"), createElement("text", {
        // for the `class` attribute, use className; or wrap the name in quotes ('class')
        'class': "cls-1",
        transform: "translate(0 29.85) scale(0.79 1)"
    }, "ama", createElement("tspan", {
        'class': "cls-2",
        x: "64.12",
        y: "0"
    }, "z"), createElement("tspan", {
        x: "79.14",
        y: "0"
    }, "on")), createElement("path", {
        'class': "cls-3",
        d: "M12.37,57c19.45,4.55,44,6.77,70.34,0,3-.77,6-1.64,8.79-2.58",
        transform: "translate(-3.46 -23.53)"
    }));
    return createElement( wp.components.Icon, { icon: svg } );
};

I hope that helps, and next time around, try asking on sites like Stack Overflow for questions like this (which is actually specific to JavaScript and not WordPress). And yes, the above code looks scary (or complex).. hence why it’s suggested you use JSX in your code, but don’t forget to build the script for production usage — building can be hard at first, but trust me, it would eventually become easy.. 🙂

tech