How can I render components with pure javascript? I used insertAdjacentHTML and forEach to render a list with objects but the objects appeared undefined.
const liRender = document.getElementById('ul-component')
function render() {
itens.forEach(() => {
liRender.insertAdjacentHTML("afterbegin",
` <li class="products-list__item">
<div class="products-list__item-thumbnail">
<img
class="product__thumbnail"
src=${itens.img}>
<div class="products-list__item-main-content">
<h4 class="product__name">
${itens.modelo}
</h4>
<p class="product__description">
${itens.description}
</p>
<div class="products-list__item-action-buttons">
<button class="button" data-open-modal="1">Detalhes</button>
</div>
</div>
</li>
`
)
})
}
export function Component() {
render()
}
Your forEach
needs iten
passed within it. Like the following,
itens.forEach((iten) => {
Then you refer to each property like so,
<p class="product__description">
${iten.description}
</p>
const liRender = document.getElementById('ul-component')
const itens = [{
modelo: 'test',
description: 'description',
img: 'image'
},
{
modelo: 'test 2',
description: 'description 2',
img: 'image'
},
{
modelo: 'test 3',
description: 'description 3',
img: 'image'
}];
function render() {
itens.forEach((iten) => {
liRender.insertAdjacentHTML("afterbegin",
` <li class="products-list__item">
<div class="products-list__item-thumbnail">
<img
class="product__thumbnail"
src=${iten.img}>
<div class="products-list__item-main-content">
<h4 class="product__name">
${iten.modelo}
</h4>
<p class="product__description">
${iten.description}
</p>
<div class="products-list__item-action-buttons">
<button class="button" data-open-modal="1">Detalhes</button>
</div>
</div>
</li>
`
)
})
}
render();
<ul id='ul-component'>
</ul>