JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

HTML

<div class='accordion-container'>

</div>

CSS

.content {
  display: none;
}

.show {
  display: block;
}

JavaScript

const container = document.querySelector('.accordion-container');

async function fetching(urlVal) {
  const response = await fetch(urlVal);
  return await response.json();
}

function handleToggle(i) {
	const allCards = document.querySelectorAll('.content');
  allCards.forEach((val, index) => {
  	if(i === index) {
    	val.classList.toggle('show');
    } else {
    	val.classList.remove('show');
    }
  })
}

function renderAccordion(data) {
	data.forEach((val, index) => {
    const holder = document.createElement('div');
    const content = document.createElement('div');
    holder.textContent = val.name;
    content.textContent = val.email;
    content.classList.add('content');
    
    holder.addEventListener('click', () => handleToggle(index))
    
    container.appendChild(holder);
    container.appendChild(content);
   })
}

function init() {
	const URL = "https://jsonplaceholder.typicode.com/users";
	fetching(URL).then(result => {
  	renderAccordion(result)
  }).catch(err => console.log(err));
}

init()