DEV Community

Cover image for How to render components in javascript?
Cample.js
Cample.js

Posted on

How to render components in javascript?

Hello everyone! Often, when creating components, the question of their rendering arises. This is a rather interesting question, the solution of which can be one of the methods described in this article.

If the component is made through a class, then a render function can be created for this component.
class Component{
constructor(selector,template,options){
this.selector=selector;
this.template=template;
this.options=options;
}
render(){
document.querySelectorAll(this.selector).forEach(
(e) => {e.insertAdjacentHTML("afterbegin",this.template);}}}
}

This function will find the selector of the corresponding tag of this component on the page, and add HTML markup to this selector.

Having created an instance of the class of this component, it can be passed to the class that calls the given render function on an instance of the component class.

class Cample {
render(options = {component}){
Object.keys(options)
.forEach((component) => {options[component].render();
});
}}

Using this method, components are rendered.

Thank you very much everyone for reading this article!

cample.js

Top comments (0)