Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a custom input with Web Components

I want to create my own set of HTML Elements with Web Components, which all include some basic functionality. I wanted to start with an input and it seems like there are two possibilities: Either inherit from HTMLElement or from HTMLInputElement.

Option A :

class BasicCustomHTMLElement extends HTMLElement {
  //basic functionality
}

class CustomInput extends BasicCustomHTMLElement {
  let shadow = this.attachShadow({
    mode: 'open'
  });

  let textbox = document.createElement("input");
  shadow.appendChild(textbox);
}

Option B

class CustomInput extends HTMLInputElement {

}

My problem with Option B ist, that I do not have a main class, where I can define basic functionality. On the other hand I have to rewrite Code in Option A for functionality that the native input and select elements offer.

Are there some aspects I am overlooking?

like image 694
J. Doe Avatar asked Jan 28 '26 21:01

J. Doe


1 Answers

There is no reason that you can't combine option A and option B so that you extend from HTMLInputElement initially with a base class and then extend that with more specific classes later.

class BasicCustomHTMLElement extends HTMLInputElement {
}

class CustomInput extends BasicCustomHTMLElement {
}

If you want a shared set of features to extend a number of built-in classes with you can use mixins.

const BaseClassMixin = (superclass) => class extends superclass {
};

class CustomInput extends BaseClassMixin(HTMLInputElement) {
}

class CustomTextArea extends BaseClassMixin(HTMLTextAreaElement) {
}

However, currently only Chrome supports extending built-in elements so it is not recommended for real-world use.

like image 73
abraham Avatar answered Jan 30 '26 11:01

abraham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!