How do I display a html component multiple times with different values from objects in an array (vanilla JS)?

I am creating a ‘portfolio site’ where I will display my projects. I am building it with JavaScript (no frameworks), HTML and SASS using Gulp. I have created an array of objects that include the project name, description etc and I want to display all projects in my portfolio.

To do this I can create all the HTML project containers (7 of them) and then give them values with textContent but that would mean I have to recreate the same 10 rows 7 times and if I add more projects I would have to write the HTML again.

I am wondering if I can create some type of ‘component’ with JavaScript that I can then add to html for each object in my array. I know this can be done with jQuery, React, Vue, Angular etc. I was wondering if there’s a way to do that with vanilla JS since I really don’t want to include any frameworks.

Hey Ron,

great question!

Yes, you can do this.

It is a two step process:

  1. Create a HTML element with createElement
  2. Add the created HTML element with appendChild
1 Like

Another way would be to use template literals:

1 Like

One of my favorite way is leveraging template literals :slight_smile:

Leveraging the easiness of creating string

// let's pretend data as
// {name: string, age: number} 
const createMyCustomElement = data => `<div class="wrapper">
<div class="wrapper__title">${data.name}</div>
<p class="wrapper__subtitle">${data.age}</p>
</div>`

Then you can use any valid method that parse string as HTML or XML like insertAdjacentHtml

document
.getElementById(".root")
.insertAdjacentHTML('beforeend', createCustomElement({name: "Bob", age: 44}))

Hope it gives you the idea :slight_smile:
Or you want to get fancy go for Web Components (mind compatibility of course) :sparkles:

2 Likes

Thanks @miku86 , @jenovs and @Marmiz for the solutions. I remember reading about Web Components a while ago so that’s what I was looking for but since there’s compatibility issues, I will go with Template Literals. I will add the code here once I implement it.

Tbh there’s compatibility issue almost with anything. :sweat_smile:
But if the only reason stopping you from using them is compatibility, well there’s an official polifill for that.

Not advocating for it, just saying it should not stop you altogether.
Hope it helps :slight_smile:

The thing is I really wanted to do this project without installing anything that I don’t necessarily need. I’m doing it in HTML, SASS and TypeScript (changed from js to test my limited knowledge). But that polyfill is great and I’ll make sure to use that together with Web Components in my next project.