Stimulus Tabs
A simple tabs controller for Stimulus.js
Codepen DemoBasic Usage
First runyarn add stimulus-tabs
to installSetup
import { Application } from "stimulus"
import TabsController from 'stimulus-tabs'
const application = Application.start()
application.register("my-tabs", TabsController)
HTML
Define each tab indata-tabs
separate each value with a space.<div data-controller="my-tabs" data-tabs="business personal"
<!-- default is selected-tab -->
data-selected-tab-class="selected-tab"
>
<a data-action="my-tabs#showBusiness" href="#">Business tab</a>
<a data-action="my-tabs#showPersonal" href="#">Personal</a>
<div class="tabs-content">
<div data-target="my-tabs.business">...</div>
<div data-target="my-tabs.personal">...</div>
</div>
</div>
Now as we click on a tab, that tab's content is revealed. That's all you need to have functional tabs.
Initial tab
By default the first tab name defined indata-tabs
will be the first tab. For example if you have
data-tabs="business personal"
business will be the first tab.You can also set the first tab in the like so:
<div data-controller="my-tabs" data-my-tabs-selected-tab="personal">
Callback
There is aselected
callback which is called when one selects a tabTo utilize it, you will need to
extend
TabsController
export default class extends TabsController {
selected() {
const htmlContent = fetchSomeData()
this.selectedContent.appendChild(htmlContent)
}
}
Geters
There are four getters which you can use (in a callback for example)this.selectedContent
returns the selected tab's content element (the target)this.selectedTab
returns the selected tab element (button for example)this.previousContent
previous returns the selected tab's content element (the target)this.previousTab
returns the previous tab element (button for example)
For initial state please use Stimulus'
connect
callback, but you must call super