HTML 코드를 작성하다 보면 <div> 태그들이 산재하여 코드가 복잡해질 때가 있습니다. 이럴 때 Web Components 기능을 사용하면 여러 개의 태그들을 하나의 커스텀 태그로 축약하여 사용할 수 있습니다. Web Components는 자바스크립트 문법이 아니라 브라우저의 기본 기능이며, 간단한 class 문법을 통해 손쉽게 커스텀 HTML 태그(컴포넌트)를 만들 수 있습니다.
예를 들어, <custom-input> 태그를 사용하면 내부에 <label>과 <input> 태그가 자동으로 생성되도록 할 수 있습니다.
class CustomInput extends HTMLElement {
connectedCallback() {
this.innerHTML = '<label>이름을 입력하쇼</label><input>';
}
}
customElements.define("custom-input", CustomInput);
CustomInput 클래스는 HTMLElement를 상속받아 커스텀 컴포넌트를 정의합니다.connectedCallback() 메서드는 해당 컴포넌트가 HTML에 삽입될 때 실행되며, 내부 HTML을 설정합니다.customElements.define("custom-input", CustomInput)를 통해 <custom-input> 태그를 등록합니다.<custom-input></custom-input>를 사용하면 자동으로 <label>과 <input> 태그가 삽입됩니다.동일한 컴포넌트를 다양한 내용으로 사용하고 싶다면 attribute를 활용할 수 있습니다.
class CustomInput extends HTMLElement {
connectedCallback() {
// 'name' attribute의 값을 가져와 변수에 저장합니다.
const name = this.getAttribute('name');
// 템플릿 리터럴을 활용해 attribute 값에 따라 다른 label을 표시합니다.
this.innerHTML = `<label>${name}을 입력하쇼</label><input>`;
}
}
customElements.define("custom-input", CustomInput);
<custom-input name="이메일"></custom-input>
<custom-input name="비번"></custom-input>
name attribute의 값을 읽어 <label> 내부에 반영합니다.<custom-input name="이메일">은 "이메일을 입력하쇼"라는 label과 input 태그가 생성됩니다.컴포넌트의 attribute가 변경될 때 특정 코드를 실행하도록 할 수도 있습니다.
class CustomInput extends HTMLElement {
connectedCallback() {
const name = this.getAttribute('name');
this.innerHTML = `<label>${name}을 입력하쇼</label><input>`;
}
// 감시할 attribute 목록을 반환
static get observedAttributes() {
return ['name'];
}
// 감시 중인 attribute가 변경될 때 호출됨
attributeChangedCallback(attributeName, oldValue, newValue) {
if(attributeName === 'name') {
// 변경 시 새로운 값을 반영해 내부 HTML 업데이트
this.innerHTML = `<label>${newValue}을 입력하쇼</label><input>`;
}
}
}
customElements.define("custom-input", CustomInput);
observedAttributes에 감시할 attribute 목록(['name'])을 명시합니다.attributeChangedCallback이 호출되어, 내부 HTML을 새 attribute 값에 맞게 업데이트합니다.observedAttributes, attributeChangedCallback)으로 실시간 업데이트가 가능함.