Skip to content

Custom Components

Brandon Jordan edited this page Sep 13, 2022 · 8 revisions

Basic components

Components are simply exported functions that pass a class instance that extends the jsUI Element class.

import {Element} from 'javascript-ui';

export function Custom() {
	return new CustomComponent();
}

class CustomComponent extends Element {
	constructor() {
		const element = document.createElement('tag');
		super(element);
		this.element = element;
	}
}

By extending Element, your element will inherit the standard methods that can be used on any HTMLElement. The CSS methods on every other Element will be added as well, as Element extends the Style class, but you can of course add your own methods to your class to add them for use with your element.

Multiple element component

If you need to create a group of elements for your element, use document fragment instead.

import {Element} from 'javascript-ui';

export function Custom() {
	return new CustomComponent();
}

class CustomComponent extends Element {
	constructor(name, options) {
		const element = new DocumentFragment();
		const tag = document.createElement('tag');
		element.append(tag);
                // and so on...
		super(element);
		this.element = element;
	}
}

The element property of your class is always expected to be an HTMLElement or DocumentFragment. Do not use DocumentFragment for only one element.

Accept child components

To create a component that can contain other components, simply accept a components argument to your exported function, then pass it to the class instance you create to set it as a components property. This will allow other components to be nested inside your component.

import {Element} from 'javascript-ui';

export function Custom(components) {
	return new CustomElement(components);
}

class CustomElement extends Element {
	constructor(components) {
		const element = document.createElement('tag');
		super(element);
		this.element = element;
                this.components = components;
	}
}

Clone this wiki locally