Nov 30 2024

Simple AlpineJS modal component


1<div
2 x-data="{show: true}"
3 x-show="show"
4 class="relative z-20"
5 aria-labelledby="modal-title"
6 role="dialog" aria-modal="true" id="{{ $id }}">
7 <template x-teleport="#{{$id}}-trigger">
8 <div x-on:click="show = !show">
9 {{ $trigger }}
10 </div>
11 </template>
12 <div class="fixed inset-0 bg-gray-900/75 transition-opacity" aria-hidden="true"></div>
13 
14 <div class="fixed inset-0 z-10 w-screen overflow-y-auto">
15 <div class="flex min-h-full items-end justify-center p-4 text-center sm:items-center sm:p-0">
16 <div
17 x-on:click.away="show = false"
18 class="w-full max-w-2xl relative transform overflow-hidden rounded-lg bg-white px-4 pb-4 pt-5 text-left shadow-xl transition-all">
19 @if (isset($header))
20 <div class="border-b border-gray-300 pb-2 mb-2">
21 {{ $header }}
22 </div>
23 @endif
24 <div>
25 {{ $slot }}
26 </div>
27 <div class="mt-5 sm:mt-6">
28 @if (isset($footer))
29 <div class="border-b border-gray-300 pb-2 mb-2">
30 {{ $footer }}
31 </div>
32 @endif
33 </div>
34 </div>
35 </div>
36 </div>
37</div>

Example

1<x-ui.modal id="new-resource-modal">
2 <x-slot name="trigger">
3 <x-button>New Resource</x-button>
4 </x-slot>
5 <x-slot name="header">
6 <h2 class="text-md font-bold">New Resource</h2>
7 </x-slot>
8 <livewire:forms.resource-form />
9</x-ui.modal>

And you can just add a div with the ID new-resource-modal-trigger wherever you want in the document and the trigger will show up there.