Last active
August 1, 2023 05:19
-
-
Save JeffreyWay/d5d86f48a527d3c3819a67cfb793926d to your computer and use it in GitHub Desktop.
Blade + Alpine.js tabs component - https://laracasts.com/series/blade-component-cookbook/episodes/9
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<x-layout> | |
<x-section> | |
<x-tabs active="First"> | |
<x-tab name="First"> | |
First content goes here. | |
</x-tab> | |
<x-tab name="Second"> | |
Second content goes here. | |
</x-tab> | |
<x-tab name="Third"> | |
Third content goes here. | |
</x-tab> | |
</x-tabs> | |
</x-section> | |
</x-layout> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@props(['name']) | |
<div x-data="{ | |
id: '', | |
name: '{{ $name }}', | |
show: false, | |
showIfActive(active) { | |
this.show = (this.name === active); | |
} | |
}" | |
x-show="show" | |
role="tabpanel" | |
:aria-labelledby="`tab-${id}`" | |
:id="`tab-panel-${id}`" | |
> | |
{{ $slot }} | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@props(['active']) | |
<div x-data="{ | |
activeTab: '{{ $active }}', | |
tabs: [], | |
tabHeadings: [], | |
toggleTabs() { | |
this.tabs.forEach( | |
tab => tab.__x.$data.showIfActive(this.activeTab) | |
); | |
} | |
}" | |
x-init="() => { | |
tabs = [...$refs.tabs.children]; | |
tabHeadings = tabs.map((tab, index) => { | |
tab.__x.$data.id = (index + 1); | |
return tab.__x.$data.name; | |
}); | |
toggleTabs(); | |
}" | |
> | |
<div class="mb-3" | |
role="tablist" | |
> | |
<template x-for="(tab, index) in tabHeadings" | |
:key="index" | |
> | |
<button x-text="tab" | |
@click="activeTab = tab; toggleTabs();" | |
class="px-4 py-1 text-sm rounded hover:bg-blue-500 hover:text-white" | |
:class="tab === activeTab ? 'bg-blue-500 text-white' : 'text-gray-800'" | |
:id="`tab-${index + 1}`" | |
role="tab" | |
:aria-selected="(tab === activeTab).toString()" | |
:aria-controls="`tab-panel-${index + 1}`" | |
></button> | |
</template> | |
</div> | |
<div x-ref="tabs"> | |
{{ $slot }} | |
</div> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment