Styling “xtype: text” in ExtJS

I decided to use the “text” ExtJS xtype the other day, and in doing so had to figure out styling.

What may seem like a very straightforward endeavor took a bit more thought than I hoped for. After attempting to apply a style from my stylesheet via the ‘cls’ or ‘baseCls’ configuration options (to no avail) I turned to the documentation and stumbled upon ExtJS selectors with the styleSelector configuration option. For whatever reason, Sencha does not mention this crucial configuration option in the overview of the class. It is necessary for styling text. You must provide a style class name that is defined in one of your stylesheets.

Next, I looked at the source code for the Ext.draw.Text class to see how it applies styling from the stylesheet, so I knew what options I could use. The code that applies styling to the text component goes like this:

/**
 * @private
 * Accumulates a style object based upon the styles specified in document stylesheets
 * by an array of CSS selectors
 */
getStyles: function(selectors) {
    selectors = Ext.Array.from(selectors);
    var i = 0,
        len = selectors.length,
        rule,
        style,
        prop,
        result = {};
 
    for (; i < len; i++) {
        // Get the style rule which exactly matches the selector.
        rule = Ext.util.CSS.getRule(selectors[i]);
        if (rule) {
            style = rule.style;
            if (style) {
                Ext.apply(result, {
                    'font-family': style.fontFamily,
                    'font-weight': style.fontWeight,
                    'line-height': style.lineHeight,
                    'font-size': style.fontSize,
                    fill: style.color
                });
            }
        }
    }
    return result;
}

So there you have the styling options you’re able to use. For large, bold and not-quite-black text, I pass the following style:

.settings-header-title {
    font-size:large !important;
    font-weight: bolder;
    color: #333333;
}

And my usage…

xtype : 'text',
text  : me.titleText,
styleSelector: '.settings-header-title'

Voila, a styled text component.