JSFiddle - React, Tailwind, and code Playground

by valkyris

HTML

<div id="tab-component" class="component-wrapper">
  <div class="component-header">
    <button class="tabA">
      TAB A
    </button>
    <button class="tabB">
      TAB B
    </button>
  </div>

  <div id="contentA">
    Content A
  </div>
  <div id="contentB" class="hidden">
    Content B
  </div>
</div>

<div id="tab-componentB" class="component-wrapper">
  <div class="component-header">
    <button class="tabA">
      TAB A
    </button>
    <button class="tabB">
      TAB B
    </button>
  </div>

  <div id="contentA">
    Content A
  </div>
  <div id="contentB" class="hidden">
    Content B
  </div>
</div>

<!--
Build a tab component using plain HTML/CSS/JavaScript.

In case you forget any API method, attribute name, etc, you can search on any reference website like MDN, etc. You are not allowed to search for the solution of the problem.

Try to use all the best practices you know about HTML, CSS and JavaScript to build this component.

Mockup:
https://i.imgur.com/Qk71XWl.jpg

Please make the component fully functional. The content can be static in the HTML.
-->

CSS

.component-wrapper {
  display: flex;
  flex-direction: column;
  border: 1px solid black;
  height: 500px;
  width: 500px;
}

.component-header {
  display: flex;
  flex-direction: row;
  border-bottom: 1px solid black;
  padding: 5px;
  justify-content: space-between;
}

.hidden {
  display: none;
}

.tabA, .tabB {
  width: 50%;
  border: none;
}

JavaScript

class Tab {
	constructor(html, content1, content2) {
  	this.component = html;
    this.tab1 = this.component.getElementsByClassName('tabA')
    console.log(this.tab1)
    this.tab1[0].addEventListener('click', () => this.clickhandler('tabA'))
    this.tab2 = document.getElementsByClassName('tabB')
    this.tab2[0].addEventListener('click', () => this.clickhandler('tabB'))
    
    this.para1 = content1;
    this.para2 = content2;
    
    this.contentA = document.getElementById('contentA')
    this.contentB = document.getElementById('contentB')
    
  }
  
  clickhandler(tab) {
    if (tab === 'tabB') {
    	this.contentA.classList.add('hidden')
			this.contentB.classList.remove('hidden')
    } else {
    	this.contentB.classList.add('hidden');
      this.contentA.classList.remove('hidden')
    }
  }
}

let tabComponent1 = new Tab(document.getElementById('tab-component'), 'hello1', 'hello2');
/* let tabComponent2 = new Tab(document.getElementById('tab-componentB'), 'hello1', 'hello2'); */