JSFiddle - React, Tailwind, and code Playground

by birdie2019

HTML

<button id="load-btn">Load Products</button>

<hr>

<ul id="list"></ul>

SCSS

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  list-style-type: none;
  letter-spacing: 1px;
}
img {
  width: 150px;
  height: 150px;
  object-fit: contain;
}

button {
  width: 100px;
  padding: 10px;
  border: 0;
  cursor: pointer;
  border-radius: 5px;
  background-color: rgb(49, 100, 172);
  color: #fff;
  transition: all 0.3s; 
  &:hover {
    background-color: rgb(255, 150, 63);
  }
}

#list {
  display: flex;
  flex-wrap: wrap;
  li {
    width: 50%;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    align-items: center;
    padding: 50px;

    span {
      text-align: center;
      color: rgb(100, 100, 100);
    }

    button {
      width: 100px;
      padding: 5px;
      margin-bottom: 5px;
    }

  }
}

JavaScript

const loadBtn = document.querySelector('#load-btn');
loadBtn.onclick = () => {
  fetch('https://fakestoreapi.com/products')
  .then(res=>res.json())
  .then(json=>{
    for (const item of json) {
      const list = document.querySelector('#list');
      const li = document.createElement('li');
      const span = document.createElement('span');
      const div = document.createElement('div');
      const img = document.createElement('img');
      const detailBtn = document.createElement('button');
      const deleteBtn = document.createElement('button');
      list.append(li);
      li.append(div);
      li.append(span);
      li.append(detailBtn);
      li.append(deleteBtn);
      div.append(img);
      span.textContent = item.title;
      img.src = item.image;
      detailBtn.textContent = 'Detail';
      deleteBtn.textContent = 'Delete';
      detailBtn.onclick = () => {
        alert(item.id);
        alert(item.category);
        alert(item.description);
      }
      deleteBtn.onclick = () => {
        let tag = event.target;
        fetch('https://fakestoreapi.com/products/6',{
          method: 'DELETE'
        })
        .then(res=>res.json())
        .then(json=>{
          tag.closest('li').remove();
        })
        .catch(error=>{
          alert('請稍候再試');
        })
      }
    }
  })
  .catch(error=>{
  	alert('抱歉,請稍後重新嘗試。');
  })
}