만들면서 학습하는 리액트(react):준비편 - 순수JS - 005

1 분 소요

준비편 - 순수JS

[순수JS 1] 탭1

요구사항

추천 검색어, 최근 검색어 탭이 검색폼 아래 위치한다

구현

  • index.html 수정
...
<html>
  ...
  <body>
    ...
    <div>
      ...
      </form>
      <div class="content">
        <div id="tab-view"></div>
        <div id="search-result-view"></div>
      </div>
    </div>
    ...
  </body>
</html>
  • TabView.js 생성
import { qs } from "../helper.js";
import View from "./View.js";

const TabType = {
  KEYWORD: 'KEYWORD',
  HISTORY: 'HISTORY',
}

const TabLabel = {
  [TabType.KEYWORD] : '추천 검색어',
  [TabType.HISTORY] : '최근 검색어',
}

export default class TabView extends View {
  constructor() {
    super(qs("#tab-view"));
    this.template = new Template();
  }

  show() {
    this.element.innerHTML = this.template.getTabList();
    super.show();
  }
}

class Template {
  getTabList() {
    return `
      <ul class="tabs">
        ${Object.values(TabTypes)
          .map(tabType => ({ tabType, tabLabel: TabLabel[tabType]}))
          .map(this._getTab)
          .join("")
        }
      </ul>
    `;
  }

  _getTab({ tabType, tabLabel }) {
    return `
      <li data-tab="${tabType}">
        ${tabLabel}
      </li>
  }
}
  • main.js 수정
...
import SearchResultView from "./views/SearchResultView.js";
import TabView from "./views/TabView.js";
...
function main() {
  ...
  const views = {
    ...,
    searchResultView: new SearchResultView(),
    tabVew: new TabView()
  }
  ...
}
  • Controller.js 수정
...
export default class Controller {
  constructor(store, { searchFormView, searchResultView, tabView }) {
    ...
    this.searchResultView = searchResultView;
    this.tabView = tabView;
    
    subscribeViewEvents();
    this.render();
  }
  ...
  render() {
    if(this.store.serachKeyword.length > 0) {
      return this.renderSearchResult();
    }

    this.tabView.show();
    
    this.searchResultView.hide();
  }

  renderSearchResult() {
    this.tabView.hide();
    this.searchResultView.show(this.store.searchResult);
  }
}

참고