Component PluginsExtending components with plugins, callback parameters, and template helpersplugGuide
Categories

Component Plugins

Plugins in Semantic UI let you extend defineComponent directly to give new functionality like i18n, state persistence, or any other features that enhance what a component can do.

With plugins you can do things like:

  • Enhance Components - Add new config options to defineComponent that get passed to your code.
  • Add Arguments to Lifecycle Callbacks - Add new top-level lifecycle arguments available to users callback arguments
  • Add Helpers - Add custom template helpers
  • Run Code on Lifecycle - Run code on component create, render, destroy, or other lifecycle events

See the Component Plugins API Reference for method signatures and options.

Using Plugins

Adding a Plugin

To enable a plugin on your app call addPlugin once in your application setup to enable a plugin and configure its application-wide settings.

Third party plugins can be used from NPM packages by calling addPlugin

Third Party Plugins
import { addPlugin } from '@semantic-ui/component';
import { ContainerQueryPlugin } from '@third-party/container-plugin'
addPlugin(ContainerQueryPlugin, { config: 'setting'});

You can also write your own plugins and import them locally

Local Plugins
import { addPlugin } from '@semantic-ui/component';
import { I18n } from './i18n-plugin.js';
import { strings } from './locales.js';
addPlugin(I18n, {
locale: 'en',
strings,
});

Using Plugins in Components

Plugins can be configured directly from defineComponent by passing a key with the plugin’s name

defineComponent({
tagName: 'my-component',
createComponent,
onCreated,
onDestroyed,
i18n: {
locale: 'en',
},
});

Some plugins might also expose new lifecycle arguments that you can access to interact with their APIs.

const events = {
'click ui-button'({ i18n, data }) {
i18n.setLocale(data.locale);
},
};

Or custom template helpers that are enabled when you activate the plugin

template.html
<h3>{t 'title'}</h3>
<p>{t 'description'}</p>

You can also access the plugin from the DOM from any component

document.querySelector('my-component').pluginName.method();

Usage Example

In this example a user has added an i18n plugin which lets them adjust currency, locale, and other configuration then read them in their component.

Authoring Plugins

Registering Plugins

registerPlugin lets a component author define their plugin. See the API Reference for further details

registerPlugin({
namespace, // how its stored on el
defaultSettings, // setting a user can write with defaults
resolveSettings, // custom resolver for user settings
createPlugin, // instance creation factory
lifecycleParams, // args to add to lifecycle events
templateData, // data values to add to templates
templateHelpers, // obj of template helpers to add
onCreated, // runs on component created
onRendered, // runs on component rendered
onDestroyed, // runs on component destroyed
appliesTo, // determines which components plugin applies to
});

Creating a Plugin

createPlugin like createComponent lets you create your plugin instance. This is used internally from any callback as self and lets you provide an external API for your plugin.

i18n-plugin.js
const createPlugin = ({ settings }) => ({
t(key) {
const { locale, prefix, strings } = settings;
const path = prefix ? `${prefix}.${key}` : key;
return get(strings[locale], path) ?? key;
},
setLocale(locale) {
settings.locale = locale;
},
});

DOM Access

Your plugin instance can be accessed outside the component from the DOM

Query
$('checkout-summary').el().i18n.setLocale('es');
Native
document.querySelector('checkout-summary').i18n.setLocale('es');

Specifying When Plugin Applies

Your plugin can use appliesTo to specify when it should be applied. This permits keywords or a function that runs once for each component to determine if its applicable

Scoping Values

Value Behavior
'components' (default) Top-level web components, plus subtemplates that explicitly set [namespace]
'all' or 'templates' Every web component and subtemplate
'configured' Only components or subtemplates that pass [namespace] in defineComponent
tagName or tagName[] Components matching the given tagName
templateName or templateName[] Components matching the given templateName

Custom Applies To

You can use a callback for appliesTo to determine at run-time whether a plugin should apply

Plugin
registerPlugin({
name: 'currencyLocale',
defaultSettings: {
language: 'en',
},
// apply if a user has `currency` in their own settings
appliesTo({ componentSettings }) {
return Boolean(componentSettings?.currency);
},
resolveSettings({ self, componentSettings }) {
return {
language: self.getLanguage(componentSettings.currency),
};
},
});
User (Plugin Used)
defineComponent({
tagName: 'money-input',
// component has currency
defaultSettings: {
currency: 'usd',
},
});
User (Plugin Not Used)
defineComponent({
tagName: 'text-input',
// not related to currency
defaultSettings: {
value: '',
},
});

Callback Parameters

lifecycleParams lets you pass your plugin’s methods or properties to component’s callback arguments received by lifecycle events like createComponent, event handlers, keybindings, and lifecycle callbacks

extendParams (see below) can be used by itself to pass through simple functions or helpers without authoring a full plugin.

Plugin
const lifecycleParams = ({ self }) => ({
t: self.t,
i18n: self, // expose whole plugin to user
});

Components can then destructure { t, i18n } directly inside any callback alongside standard arguments like state and data:

User
const events = {
'click ui-button'({ i18n, data }) {
i18n.setLocale(data.locale); // call a plugin API
},
};

Template Helpers

Use templateHelpers to register custom template helpers that components can call inside their templates.

Unlike global helpers registered with registerHelpers, passing a function to templateHelpers scopes the helpers to each component instance so {t 'title'} automatically resolves against that component’s own plugin settings:

Plugin
const templateHelpers = ({ self }) => ({
t: self.t,
});
User Template
<h3>{t 'title'}</h3>
<p>{t 'subtotal'}</p>

Template Data

Use templateData to add values to a component’s data context so they can be read directly inside template expressions.

Plugin
const templateData = ({ settings }) => ({
locale: () => settings.locale,
});
User Template
{#if is locale 'en'}
<span>{locale}</span>
{/if}

Plugin Settings

Plugin settings let you specify settings that a downstream user can set on their component.

Plugin
registerPlugin({
name: 'i18n',
defaultSettings: {
lang: 'en',
},
});
User
defineComponent({
i18n: {
lang: 'es', // component uses a diff lang
},
tagName,
createComponent,
// rest
});

Advanced Plugin Settings

If you need to customize how a user’s settings are applied to your plugin use resolveSettings.

User
defineComponent({
i18n: 'es', // shorthand use
tagName,
createComponent,
// rest
});
Plugin
registerPlugin({
name: 'i18n',
defaultSettings: {
lang: 'en',
},
// shorthand supported
resolveSettings({ settings, config }) {
if (isString(config)) {
settings.lang = config;
}
},
});

Extending Callbacks

If you want to just provide additional component lifecycle params without writing a full plugin you can use extendParams.

Plugin
import { extendParams } from '@semantic-ui/component';
extendParams({
setCurrency: (code) => currency.set(code),
});

Users can then access those new params from any part of a component to call your plugins code.

User
defineComponent({
events: {
'click [data-currency]'({ setCurrency, data }) {
setCurrency(data.currency);
},
},
});

Per-Component Parameters

Parameters themselves can use a callback function to make their behavior vary depend on how its called.

This can be used to change behavior based on the DOM el, state, or settings, or whatever else you can dream up.

extendParams(({ el }) => ({
track: (event, data) => analytics.send(el?.tagName, event, data),
}));

Extend Params Example

Previous
Server Side Rendering
Next
Specs