Flowbite JavaScript API
Flowbite는 JavaScript로 datepicker, dropdown, modal 등 더 복잡한 UI 컴포넌트의 인터랙티비티를 구동하면서 동시에 Tailwind CSS의 유틸리티 클래스를 활용합니다. JavaScript로 인터랙티브 UI 컴포넌트를 구동하는 방법은 크게 두 가지예요. (1) data 속성 인터페이스를 쓰고 NPM 또는 CDN으로 Flowbite JavaScript를 포함하거나, (2) 프로그래밍 방식으로 UI 컴포넌트 인스턴스를 만들고 메서드를 호출해 요소에 이벤트를 연결하는 방법입니다.
출처: 문서
본문
Flowbite API
Flowbite는 TypeScript 선택 지원과 함께 JavaScript로 작성되며, 인터랙티브 UI 컴포넌트를 위한 광범위한 API를 제공합니다. 객체의 새 인스턴스를 만들고, 다양한 옵션으로 설정하고, show나 hide 같은 메서드를 호출하거나 전역 인스턴스 매니저에 접근해 초기화된 객체를 가져올 수 있어요.
예를 들어 Modal 컴포넌트를 객체로 만들고 옵션을 지정해 보겠습니다. 먼저 모달 요소와 옵션을 정의합니다.
// 모달 메뉴 요소를 설정합니다
const $targetEl = document.getElementById('modalEl');
// 기본값이 있는 옵션
const options = {
placement: 'bottom-right',
backdrop: 'dynamic',
backdropClasses: 'bg-gray-900/50 dark:bg-gray-900/80 fixed inset-0 z-40',
closable: true,
onHide: () => { console.log('modal is hidden'); },
onShow: () => { console.log('modal is shown'); },
onToggle: () => { console.log('modal has been toggled'); }
};
그다음 위 옵션을 바탕으로 새 Modal 객체를 만듭니다.
import { Modal } from 'flowbite';
/*
* $targetEl: 필수
* options: 선택
*/
const modal = new Modal($targetEl, options);
show()와 hide() 메서드로 JavaScript에서 직접 모달 컴포넌트를 보여주거나 숨길 수 있고, toggle() 메서드로 가시성을 토글할 수 있습니다.
// 모달 보이기
modal.show();
// 모달 숨기기
modal.hide();
// 모달 토글
modal.toggle();
// set the modal menu element
const $targetEl = document.getElementById('modalEl');
// options with default values
const options = {
placement: 'bottom-right',
backdrop: 'dynamic',
backdropClasses: 'bg-gray-900/50 dark:bg-gray-900/80 fixed inset-0 z-40',
closable: true,
onHide: () => {
console.log('modal is hidden');
},
onShow: () => {
console.log('modal is shown');
},
onToggle: () => {
console.log('modal has been toggled');
}
};
import { Modal } from 'flowbite';
/*
* $targetEl: required
* options: optional
*/
const modal = new Modal($targetEl, options);
// show the modal
modal.show();
// hide the modal
modal.hide();
// toggle the modal
modal.toggle();
// true if hidden
modal.isHidden();
// true if visible
modal.isVisible();
<!-- Main modal -->
<div id="modalEl" tabindex="-1" aria-hidden="true" class="hidden overflow-y-auto overflow-x-hidden fixed top-0 right-0 left-0 z-50 justify-center items-center w-full md:inset-0 h-[calc(100%-1rem)] max-h-full">
<div class="relative p-4 w-full max-w-2xl max-h-full">
<!-- Modal content -->
<div class="relative bg-neutral-primary-soft border border-default rounded-base shadow-sm p-4 md:p-6">
<!-- Modal header -->
<div class="flex items-center justify-between border-b border-default pb-4 md:pb-5">
<h3 class="text-lg font-medium text-heading">
Terms of Service
</h3>
<button type="button" class="text-body bg-transparent hover:bg-neutral-tertiary hover:text-heading rounded-base text-sm w-9 h-9 ms-auto inline-flex justify-center items-center" data-modal-hide="modalEl">
<svg class="w-5 h-5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18 17.94 6M18 18 6.06 6"/></svg>
<span class="sr-only">Close modal</span>
</button>
</div>
<!-- Modal body -->
<div class="space-y-4 md:space-y-6 py-4 md:py-6">
<p class="leading-relaxed text-body">
With less than a month to go before the European Union enacts new consumer privacy laws for its citizens, companies around the world are updating their terms of service agreements to comply.
</p>
<p class="leading-relaxed text-body">
The European Union’s General Data Protection Regulation (G.D.P.R.) goes into effect on May 25 and is meant to ensure a common set of data rights in the European Union. It requires organizations to notify users as soon as possible of high-risk data breaches that could personally affect them.
</p>
</div>
<!-- Modal footer -->
<div class="flex items-center border-t border-default space-x-4 pt-4 md:pt-5">
<button data-modal-hide="default-modal" type="button" class="text-white bg-brand box-border border border-transparent hover:bg-brand-strong focus:ring-4 focus:ring-brand-medium shadow-xs font-medium leading-5 rounded-base text-sm px-4 py-2.5 focus:outline-none">I accept</button>
<button data-modal-hide="default-modal" type="button" class="text-body bg-neutral-secondary-medium box-border border border-default-medium hover:bg-neutral-tertiary-medium hover:text-heading focus:ring-4 focus:ring-neutral-tertiary shadow-xs font-medium leading-5 rounded-base text-sm px-4 py-2.5 focus:outline-none">Decline</button>
</div>
</div>
</div>
</div>
초기화 함수 (Init functions)
data 속성을 사용할 때 초기화 함수를 프로그래밍 방식으로 호출하고 싶다면(DOM이 다시 렌더링된 뒤 호출 등) JS 코드 어디에서든 initFlowbite() 함수를 쓰거나 initModals(), initDropdowns() 같은 개별 컴포넌트 초기화 함수를 사용할 수 있어요.
import { initFlowbite } from 'flowbite'
// 컴포넌트 초기화
initFlowbite();
<script type="application/javascript">
import { initFlowbite } from 'flowbite'
// initialize components based on data attribute selectors
initFlowbite();
</script>
인스턴스 매니저 (Instance manager)
버전 2.0.0부터 Flowbite JS API는 data 속성 인터페이스로 만든 인스턴스까지 포함해 모든 인스턴스에 전역으로 접근할 수 있는 방법을 제공합니다. 이렇게 하면 컴포넌트를 프로그래밍 방식으로 다루면서도 권장되는 빠른 data 속성 인터페이스를 그대로 쓸 수 있어요.
// 예: 모든 Dropdown 인스턴스에 접근
import { Dropdown } from 'flowbite';
const dropdowns = Dropdown.getAllInstances ? Dropdown.getAllInstances() : [];
window.addEventListener('load', function() {
const modal = FlowbiteInstances.getInstance('Modal', 'modal-id');
})
// show the modal
modal.show();
// hide the modal
modal.hide();
// remove the instance object from the global FlowbiteInstances manager
modal.removeInstance();
modal.destroyAndRemoveInstance();
const tooltip = FlowbiteInstances.getInstance('Tooltip', 'tooltip-id');
// show the tooltip
tooltip.show();
// hide the tooltip
tooltip.hide();
// destroy the tooltip event listeners
tooltip.destroy();
// re-init the tooltip object and event listeners
tooltip.init();
// show the tooltip
tooltip.show();
FlowbiteInstances.getAllInstances();
FlowbiteInstances.getInstances('Modal');