1

How can I render components with pure javascript? I used insertAdjacentHTML and forEach to render a list with objects but the objects appeared undefined.

object list

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()
}

result list return undefined

Davi Roque
  • 25
  • 4
  • Please provide a [mcve]. There's no way we can tell, from the code you provided, why those properties are `undefined`. – Quentin Jul 28 '22 at 16:45

1 Answers1

0

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>
Loktar
  • 34,764
  • 7
  • 90
  • 104