Creating a collapsable component with Alpine

February 23, 2022

Expected result from code:

expected tooltip result

This the the whole code for the component:

<div x-data="{collapsable: true, collapsed: false}">
    <div class="pb-4 sm:flex sm:items-center sm:justify-between">
        <h3 class="text-2xl leading-6 font-medium text-gray-800 cursor-pointer" x-on:click="collapsed = !collapsed">
            Some title here

        <div x-cloak x-show="collapsable" class="mt-3 sm:mt-0 sm:ml-4 cursor-pointer" x-on:click="collapsed = !collapsed">
            <span x-show="collapsed">
                <svg xmlns="" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
            <span x-show="!collapsed">
                <svg xmlns="" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                  <path fill-rule="evenodd" d="M14.707 12.707a1 1 0 01-1.414 0L10 9.414l-3.293 3.293a1 1 0 01-1.414-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 010 1.414z" clip-rule="evenodd" />

        x-transition:enter="transition ease-out duration-300 transform origin-top-right"
        x-transition:enter-start="opacity-0 scale-y-0"
        x-transition:enter-end="opacity-100 scale-y-100"
        x-transition:leave="transition ease-in duration-200 transform origin-top-right"
        x-transition:leave-start="opacity-100 scale-y-100"
        x-transition:leave-end="opacity-0 scale-y-0"
        class='overflow-hidden bg-white shadow-sm rounded-md sm:rounded-lg',
        <div class="m-auto px-4 py-5">
            Your content here

Mauro Baptista

Mauro Baptista

Building stuff with code and having fun in the way

© 2022, Built with Gatsby